Restricting access can be based on a permission, some checks, or a different location for the login view, which are implemented in much the same way.
The general approach is to run the check directly on the request.user of the view. For example, the following view confirms that the user is logged on and has Polls.can_vote permissions:
def vote (Request): if request.user.is_authenticated () and Request.user.has_perm (' Polls.can_vote '): # vote here else: return HttpResponse ("You can ' t vote in this poll.")
And Django has a neat way of calling User_passes_test. It takes parameters and then generates adorners for the situation you specify.
def user_can_vote (user): Return user.is_authenticated () and User.has_perm ("Polls.can_vote") @user_passes_test (user_ Can_vote, login_url= "/login/") def vote (Request): # Code Here can assume a logged-in user with the correct permission. ...
User_passes_test uses a required parameter: A callable method that returns True when a user object exists and is allowed to view the page. Note User_passes_test does not automatically check the user
If you are certified, you should do it yourself.
In the example we also show the Second optional parameter, Login_url, which lets you specify the URL of your login page (default is/accounts/login/). If the user does not pass the test, then user_passes_test redirects the user to Login_url
Since checking whether a user has a special permission is a relatively common task, Django provides a shortcut for this scenario: the permission_required () adorner. Using this adorner, the previous example can be rewritten as:
From django.contrib.auth.decorators import permission_required@permission_required (' Polls.can_vote ', login_url= "/ Login/") def vote (Request): # ...
Note that permission_required () also has an optional login_url parameter, which defaults to '/accounts/login/'.
Restricting access to common views
The most frequently asked question in the Django User mailing list is about restrictive access to the common view. To implement this feature, you need to wrap the view yourself, and in urlconf, replace your own version with a common view:
From django.contrib.auth.decorators import login_requiredfrom django.views.generic.date_based import object_ Detail@login_requireddef Limited_object_detail (*args, **kwargs): Return Object_detail (*args, **kwargs)
Of course, you can replace login_required with any other qualifier modifier.