Here are additional resources about Python decorators and Django user management:
Implementing Django View Authorization
00:15 What do you do if the user isn’t logged in or doesn’t have access? If the user isn’t logged in, then it would be nice to send them to the login page and then when they’re done logging in, bring them back to where they were. Doing so involves a fair amount of logic, but luckily Django comes with some tools to help you do it quickly.
00:35 Restricting Views to Logged-in Users. Django supports different ways of controlling what users can see and do. It includes a full mechanism for groups and permissions and a lighter-weight system based on users’ accounts. This course will focus on the latter.
00:53 Python has a feature called decorators. A decorator is a way of wrapping a function with another function. Django uses these decorators to help enforce authentication. For more about how decorators work, check out the Primer on Python Decorators.
01:11 In Django, you use decorators to wrap your view. The decorator then gets called before your view and can stop your view from being called if necessary. This is useful for authentication as it checks whether to let a user actually visit the view. Here’s the syntax.
This code shows the use of the
@login_required decorator. When the
private_place() view function is called, the Django
login_required() wrapper function is called first. The decorator checks whether a user is authenticated and if they aren’t, it sends them to the login page.
Until now, you’ve been using the admin site’s authentication mechanism. This only works if you’re going to the admin site. If you go there and log in, you’ll be able to visit the
/private_place/ URL seen onscreen now.
However, if you go straight to the
/private_place/ without logging in, then you’ll get an error. Django comes with tools for authenticating, but it doesn’t know what your website looks like, so it doesn’t ship with a regular login page.
This allows you to take advantage of all of Django’s built-in authentication views. You’ll also need a corresponding login template. Create a
registration/ subfolder in the
templates/ folder, and then create
login.html inside it.
The login redirect will now work correctly when you visit the
/private_place/ URL. Additionally, by adding
django.contrib.auth.urls, you now have
/accounts/logout/ available as well, as seen onscreen here.
Become a Member to join the conversation.