Need help understanding Django authentication code

Viewed 38

Code from views.py:

from django.contrib.auth.decorators import login_required 

@login_required
def index(request):
    user = request.user 
    posts = Post.objects.filter(user=user) 

I can't understand the inline @login_required. Why should we use this decorator?

And what about user = request.user? In this project, we hadn't created a model named user.

Please explain this to me. Thanks a lot!

2 Answers

In this code I can't understand inline @login_required Why should we use the decorator

The @login_required decorator does exactly what it says: it requires a user to log in when accessing the route associated with this view.

And user=request.user user ?? In this project, we hadn't created models named user.

Django defines a User model fore you.

For more details about the default authentication and authorization system, read the documentation. Googling something like "django login_required" gives a wealth of information.

The logic behind this function is to achieve that only the logged-in user has access to the posts he wrote himself: all http requests contain the id of the user: if he is not logged in, he is identified as anonymous, otherwise as user. To get his identification, you call request.user and then pass it to the query to call his posts. Therefore : neither an anonymous user nor another user can get access to the full list of posts of a third user.

Related