Summary: user permission module in Django

Source: Internet
Author: User

 

Summary: User Authentication in Django
Http://www.djangoproject.com/documentation/authentication/

This module consists
User (users)
Permission (permissions)
Group)
Message)

These are both literally understandable, but I am not very familiar with messages ............

1. Installation
1) Add 'django. contrib. auth' to installed_apps of setting. py.
2) install the database manage. py syncdb.
In fact, the user permission module is an app that Django has already written, so it also has its own models, so it needs to synchronize the database.

 

2. UseR
1) attributes
It contains the user class and has the following fields
Username, first_name, last_name, email, password, is_staff (whether you have the permission to access website management ),
Is_active, is_superuser, last_login, date_joined.

This is the basic information of the user that comes with Django. To use this permission module, you must use its user class,
However, our user information usually has other attributes. In this case, we can add another type of extension. The relationship between the class and the user is onetoone.
For example:
# This is the code in China-Django.

Class profile (models. Model ):
User = models. onetoonefield (User)

Blog = models. charfield (maxlength = 128, blank = true)
Location = models. charfield (maxlength = 128, blank = true)
Occupation = models. charfield (maxlength = 64, blank = true)

Reward = models. integerfield (default = 0, blank = true)
Topic_count = models. integerfield (default = 0, blank = true)
Post_count = models. integerfield (default = 0, blank = true)

Class admin:
List_display = ('user', 'blog ', 'location', 'occupation', 'reward', 'topic _ count', 'Post _ count ')

2) Method
Here are several main methods
Is_anonymous (): whether it is an anonymous user. If you have already logged in, this method always returns false.
Is_authenticated (): whether the user has been verified, that is, whether the user name and password exist.
Get_group_permissions (): obtains the permissions of all groups to which the user belongs.
Get_all_permissions (): Get all permissions of the user.
Has_perm (Perm): determines whether the user has specific permissions. the perm format is appname. codename.
Email_user (subject, message, from_email = none): send an email to a user.

3) anonymoususer
Anonymoususer is inherited from the user interface, but it is different from the user interface:
The ID attribute is none.
Is_anonymous () returns always true
Is_authenticated () returns always false
Has_perm () returns always false
Set_password (), check_password (), save (), delete (), set_groups (), and set_permissions () both trigger notimplementederror errors.

3. user verification
1) Login)

From Django. contrib. Auth import authenticate, Login

Def my_view (request ):
Username = request. Post ['username']
Password = request. Post ['Password']
User = authenticate (username = username, password = PASSWORD)
If user is not none:
Login (request, user)
# Redirect to a success page.
Else:
# Return an error message.

First, we need to verify the user and then log in. After successful login, we can get the user object currently logged in through request. User.

2) log out (logout)

From Django. contrib. Auth import logout

Def logout_view (request ):
Logout (request)
# Redirect to a success page.

3) restrict access by illegal users
The most common method is to determine through request. User. is_authenticated ().

From Django. Http import httpresponseredirect

Def my_view (request ):
If not request. User. is_authenticated ():
Return httpresponseredirect ('/login /? Next = % s' % request. Path)
#

Another quick method is login_required.

From Django. contrib. Auth. decorators import login_required

@ Login_required
Def my_view (request ):
#

In this way, when you access my_view, you need to pass the verification.
/Accounts/login /? Next =/polls/3/
The currently accessed page is used as a parameter, and three context variables are passed.
Form: A formwrapper object used to reconstruct the login form
Next is the current page you visit.
Site_name: the current site name. Set the value of site_id in setting. py.

In addition, we need to configure the/accounts/login path in your URLs.
There are two types of templates. The difference is that different templates are used. The first method is registration/login.html template by default, and the second method is custom template.

(R' ^ accounts/login/$ ', 'django. contrib. Auth. Views. login '),
(R '^ accounts/login/$', 'django. contrib. Auth. Views. login', {'template _ name': 'myapp/login.html '}),

Example of a login.html template:

{% Extends "base.html" %}

{% Block content %}

{% If form. has_errors %}
<P> your username and password didn't match. Please try again. </P>
{% Endif %}

<Form method = "Post" Action = ".">
<Table>
<Tr> <TD> <label for = "id_username"> Username: </label> </TD> <TD >{{ form. username }}</TD> </tr>
<Tr> <TD> <label for = "id_password"> password: </label> </TD> <TD >{{ form. password }}</TD> </tr>
</Table>

<Input type = "Submit" value = "login"/>
<Input type = "hidden" name = "Next" value = "{next}"/>
</Form>

{% Endblock %}

4) whether the user has Access Permissions

After a class with the class admin: internal class is created, the system automatically adds, create, and delete permissions. However, you can also define permissions by yourself.
As follows:

Class uscitizen (models. Model ):
#
Class meta:
Permissions = (
("Can_drive", "can drive "),
("Can_vote", "can vote in elections "),
("Can_drink", "can drink alcohol "),
)

In this way, three custom permissions are defined for the uscitizen class. The first is codename and the second is discription.

After the permission is defined, we can use user. has_perm to determine whether the permission is granted.

Def my_view (request ):
If not (request. User. is_authenticated () and request. User. has_perm ('lls. can_vote ')):
Return httpresponse ("you can't vote in this poll .")

The has_perm parameter should be appname (packname) +. + codename

There is also a simpler method, as shown below:
@ User_passes_test (lambda U: U. has_perm ('lls. can_vote '))
In this way, if the user does not have the permission, the user will automatically jump to/accounts/login/or custom jump
@ User_passes_test (lambda U: U. has_perm ('lls. can_vote '), login_url ='/login /')

 

4. User Authentication in Template
Users

{% If user. is_authenticated %}
<P> welcome, {user. Username}. Thanks for logging in. </P>
{% Else %}
<P> welcome, new user. Please log in. </P>
{% Endif %}

Permissions
{Perms. Foo}. If a logged-in user has any permissions on the foo app, {perms. Foo} is equal to true, and false
{Perms. Foo. can_vote}. This is clear...
Example:

 

{% If perms. Foo %}
<P> you have permission to do something in the foo app. </P>
{% If perms. Foo. can_vote %}
<P> you can vote! </P>
{% Endif %}
{% If perms. Foo. can_drive %}
<P> you can drive! </P>
{% Endif %}
{% Else %}
<P> You don't have permission to do anything in the foo app. </P>
{% Endif %}

5. Authentication backends
The verification of Django squadron users is based on their own modules, and other modules can also be used.
The default authentication_backends is
('Django. contrib. Auth. backends. modelbackend ',)

We can write a different user authentication method, but it must have the get_user and authenticate methods.
For example:

From Django. conf import settings
From Django. contrib. Auth. Models import user, check_password

Class settingsbackend:
"""
Authenticate against the settings admin_login and admin_password.

Use the login name, and a hash of the password. For example:

Admin_login = 'admin'
Admin_password = 'sha1 $4e987 $ afbcf42e21bd1_fb71db8c66b321e9fc33051de'
"""
Def authenticate (self, username = none, password = none ):
Login_valid = (settings. admin_login = username)
Pwd_valid = check_password (password, settings. admin_password)
If login_valid and pwd_valid:
Try:
User = user. Objects. Get (username = username)
Users T User. doesnotexist:
# Create a new user. Note that we can set password
# To anything, because it won't be checked; the password
# From settings. py will.
User = user (username = username, password = 'get from settings. py ')
User. is_staff = true
User. is_superuser = true
User. Save ()
Return user
Return none

Def get_user (self, user_id ):
Try:
Return user. Objects. Get (PK = user_id)
Users T User. doesnotexist:
Return none

In this case, we need to modify setting.
Authentication_backends = (
'Sputnik. backends. ldapbackend. ldapbackend ',
)

Here is an article about authentication backends.

LDAP authentication in Django with backends

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.