Skip to content
Advertisement

How to stop having anonymous user in django

So I have a django project and there is one view(home view) which displays the posts of the followed users and that requires a user to be authenticated, if there is no user loged in, then the code returns a ‘AnonimousUser’ is not iterable error and I will like my code to redirect the anonymous user to the login page if the person is on the home view. After some investigation I realized that this can be done with a custom middleware but I dont know how to do it so currently that middleware just prints if a user is logged in or if it is anonymous. What can I do to Complete this middleware and get rid of that Anoniomus User error?

middleware.py

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        response = self.get_response(request)
        return response
    def process_view(self, request, view_func, view_args, view_kwargs):
        if(request.user.is_authenticated):
            print(Authenticated")
        else:
            print("Anonimous user")

views.py

def home(request):
    user = Following.objects.get(user=request.user)
    followed_users = [i for i in user.followed.all()]
    followed_users.append(request.user)

    contents = Post.objects.filter(user__in = followed_users)

    context = {
        "contents": contents,
    }
    print("nice")
    return render(request, 'home.html', context)

urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('login', views.login, name='login'),
    path('register', views.register, name='register'),
    path('logout', views.logout, name='logout'),
    path('<username>/', views.profile, name='profile'),
]

If you have any questions or need to see more code please let me know;)

Advertisement

Answer

There is no required to writing a custom middleware.

You can restrict the anonymous user in your view like this

def home(request):
    if not request.user.is_authenticated:
        return redirect  ('your_login_url')
    user = Following.objects.get(user=request.user)
    followed_users = [i for i in user.followed.all()]
    followed_users.append(request.user)

OR you can user login_required decorator

from django.contrib.auth.decorators import login_required

@login_required(login_url='your_login_url')
def home(request):
    user = Following.objects.get(user=request.user)
    followed_users = [i for i in user.followed.all()]
    followed_users.append(request.user)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement