[Answer]-Check if user is authenticated in urls.py

0đź‘Ť

âś…

Authentication checks should be performed in the view, that’s where checks and security are ment to exist.

Apart from that you can decorate Class Based Views in urls to check for login, but the most common / sensible / usual approach is to make that check in the view.
If you are using Class Based Views then you could create a Mixin which checks if the user is authenticated, this combined with the tools Django Offers, allow you to redirect the user to the appropriate view (login, or if check is passed allow him to view the requested url).

If you are using function based views, then Django offers decorators for those functions to provide common “needs” of a web framework.

PS If you are using CBV’s then django-braces has already a few wonderful mixins available for common tasks (Ajax, Security etc).

👤petkostas

1đź‘Ť

This is not right way to implement it.
The best solution is to wrap your views with @login_requered decorator.

Example:

@login_required
def home_page(request):
     ...

You can specify in your settings.py LOGIN_URL where user will be redirected if not authorized.
Please read more at django documentation

👤DAKZH

Leave a comment