Django Framework Chapter (10): Django's Own authentication system

Source: Internet
Author: User

Django's own user authentication

When we develop a website, it is unavoidable to design the user system that implements the website. At this time we need to implement including user registration, user login, user authentication, logout, change password and other functions, this is really a troublesome thing.

Django, as the ultimate framework for perfectionism, will of course think of the user's pain points. It has built-in a powerful user authentication system,--auth, which uses the Auth_User table to store user data by default.

Back to top auth module
Import Auth

A number of practical methods are available in Auth:

Authenticate ()

Provides the user authentication function, namely verifies the user name and the password is correct, generally needs username, password two keyword parameter.

If the authentication succeeds (the username and password are valid), a user object is returned.

Authenticate () sets a property on the user object to identify that the backend has been authenticated, and that information is required during subsequent logons.

Usage:

user = Auth.authenticate (request,username='theuser', password='thepassword')  
Login (httprequest, user)

The function accepts a HttpRequest object, and a certified user object.

This function implements the function of a user login. It essentially generates the relevant session data for the user at the backend.

Usage:

From Django.contrib.authImportAuthenticate, LoginDefMy_view (Request): username = Request. post[ "username " password = Request. Post[ "password"  "user = Authenticate (request, Username=username, Password=if user is not< Span style= "COLOR: #000000" > None:login (request, user) # Redirect to a success page.  ... else: # Return an ' invalid login ' error message. ... 
Logout (Request)

The function accepts a HttpRequest object with no return value.

When the function is called, the session information for the current request is cleared. Even if the user is not logged in, using this function will not error.

Usage:

Import logout   def Logout_view (Request):  logout (Request)  # Redirect to a success Page.    
is_authenticated ()

Used to determine whether the current request passed authentication.

Usage:

def My_view (Request): not   request.user.is_authenticated ():    return Redirect ('%s? next=%s'% (settings. Login_url, Request.path))      
Login_requierd ()

Auth provides us with an adorner tool that is used to quickly add login checks to a view.

Usage:

Import login_required      @login_requireddef My_view (Request):  ...  

If the user is not logged in, it jumps to the Django default login URL '/accounts/login/' and passes the absolute path of the current access URL (redirected to the path after successful login).

If you need to customize the URL of the login, you need to modify it through Login_url in the settings.py file.

Example:

'/login/'  # is configured here to route your project login page   
Create_user ()

Auth provides a method for creating a new user, which needs to provide the necessary parameters (username, password), etc.

Usage:

Import Useruser = User.objects.create_user (username=' username ', password=' password ', email=' Mailbox ',... )         
Auth provides a way to create a new super-user that needs to provide the necessary parameters (username, password), and so on.

Usage:

Import Useruser = User.objects.create_superuser (username=' user name ', password=' password ', email= ' mailbox ',... )         
check_password (password)

Auth provides a way to check if the password is correct and needs to provide the user's password for the current request.

The password returns true correctly, otherwise false is returned.

Usage:

OK = User.check_password (' password ')  
set_password (password)

Auth provides a way to change the password, receiving the new password to be set as the parameter.

User Object properties: Username, password

Is_staff: Whether the user has administrative privileges on the site.

Is_active: Whether to allow users to log on, set to False, you can prevent users from logging on without deleting the user.

Go back to the top extend the default Auth_User table

This built-in authentication system is so easy to use, but the Auth_User table field is fixed, and I can't get it directly in the project!

For example, I want to add a field that stores the user's phone number, what should I do?

Smart you might think of creating a new table and then associating it with a one-to-ones and built-in auth_user table, so that you can meet the requirements but is there a better way to implement it?

The answer is of course there is.

We can define a model class of our own by inheriting the built-in Abstractuser class.

This allows for flexible design of user tables based on project requirements and the use of Django's powerful authentication system.

Import Abstractuserclass UserInfo (Abstractuser): "" "" ""     nid = models. Autofield (primary_key=True) phone = models. Charfield (max_length=11, null=true, unique=__str__return self.username      

Attention:

After extending the built-in Auth_User table as described above, be sure to tell Django in settings.py that I am now using my newly defined userinfo table to authenticate the user. The wording is as follows:

#"app name. UserInfo"  

Note again:

Once we have specified the table used by the new authentication system, we need to re-create the table in the database and not continue to use the original default Auth_User table.

Details can be seen https://www.cnblogs.com/maple-shaw/articles/9537320.html?tdsourcetag=s_pcqq_aiomsg

Django Framework Chapter (10): Django's Own authentication system

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.