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

JavaScript

views.py

JavaScript

urls.py

JavaScript

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

JavaScript

OR you can user login_required decorator

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement