Django Framework-auth Components

Source: Internet
Author: User

Django's own user authentication

We are in the development of a website, there is no need to design the implementation of the website user system, 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.

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

Auth Module

Auth Essence is a Django app, inside there are views,models and so on .

 from Import Auth

There are a number of practical methods available in Auth:

Authenticate ()

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

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:

 from Django.contrib  import= auth.authenticate (Request, Username='  China', password='bigcountry') Note: The default is to validate the Auth_User table, where the field name is username, Password, if it's a custom field, you don't have to use Username,password. 
Login (HttpRequest, user_obj)

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

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

 fromDjango.contrib.authImportAuthenticate, LogindefMy_view (Request): Username= Request. Post.get ('username') Password= Request. Post.get ('Password') User= Authenticate (Request, Username=username, password=Passwrod)ifUser is   notNone:login (Request, user)#jump to the page after successful login        Else:            #returns information for a login failure
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:

 from  Django.contrib.auth   Import  logoutdef   Logout_view (Request):    Logout ( Request)    #  jump to pre-set page after logout, such as login page or homepage
Is_authenticated ()

Used to determine whether the current request passed authentication.

Usage:

def   My_view (Request):     if not Request.user. Is_ Authenticated ():        return  Redirect ("{}?next={}". Format (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:

 from Import login_required@login_required def   Home (Request):    Pass

If the user is not logged in, it jumps to the Django default login url "/accounts/login/" and passes the absolute brutishness 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 Lofin_url in the settings.py file.

Example:

  # This is configured as a route for your project login page

Create_user ()

Auth provides a way to create a new user, need to provide the necessary parameters (Username,password), and so on.

Usage:

 from Import  = User.objects.create_user (username=' username ', password=' password ' , email= ' Mail ',...)
Create_superuser ()

Auth provides a way to create a new Superuser (administrator), need to provide the necessary parameters (Username,password, email) and so on.

 from Import  = User.objects.create_superuser (username=' username ', password=' password ', email= ' mail ',...)

# must provide a mailbox, by default is the mailbox when the login name of the
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:

Flag = User_obj.check_password (' password ')
Set_password (password)

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

Note: Be sure to invoke the Save method of the User Object!!!

Usage:

User.set_password (password='new_password') user.save ()
A simple example of a password change feature
 fromDjango.contrib.auth.decoratorsImportlogin_required@login_requireddefSet_password (Request): User=Request.user err_msg="'content={"err_msg": err_msg}ifRequest.method = ='POST': Old_password= Request. Post.get ('Old_password',"') New_password= Request. Post.get ('New_password',"') Repeat_password= Request. Post.get ('Repeat_password')        #Check that the old password is correct        ifUser.check_password (old_password):if   notnew_password:err_msg='The new password cannot be empty'            elifNew_password! =repeat_password:err_msg='changed password two times inconsistent'            Else: User.set_password (New_password) user.save ()returnredirect'/login/')        Else: Err_msg='Original Password input error'    returnRender (Request,'set_password.html', content)
Properties of the User object

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

Extend the default Auth_User table!!!

Although the built-in authentication system is very useful, but the Auth_User table fields are fixed, we can not be used in the project directly to use, if you want to add a user cell phone number field, how to do?

Perhaps you might think of creating a new table and then associating it with a one-to-ones and built-in Auth_User table, which is a bit of a hassle, though it satisfies the requirements.

So Django provides us with a way to customize the user table by inheriting the built-in Abstractuser class to define a model class of its own.

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

------app's models.py file from import  abstractuserclass  UserInfo ( Abstractuser):    "" "     user     Information table" "= models. Autofield (primary_key=True)    = models. Charfield (max_length=11, null=true, unique=True)        def__str__(self):         return Self.username

Attention:

After extending the built-in Auth_User table as described above, be sure to inform Django in settings.py that we are now using our newly defined UserInfo table for user authentication, as follows:

# refer to the user table that Django comes with, which you need to set when you inherit it ' The app name. UserInfo'

Ps: 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.

1 Auth Components2 3 Create user, verify login4 5  fromDjango.contribImportAuth6 7 auth_user Table:8 Is_staff is the status of the employee, specifies whether the user can log in to the admin background9 is_activeTen Is_superuser One  A Create a Super Administrator - python manage.py createsuperuser -  the Certified Users -User_obj = auth.authenticate (Request, Username=username, password=password) -  - When authentication is passed, a user object is returned, and the error returns none +  - Logging Login Status + The actual creation session, therefore AUTH middleware, relies on the session middleware, therefore the session middleware registration order needs before, A Auth.login (request,user_obj) at  - Log off, delete session - auth.logout (Request) -  - View user logon status - request.user.is_authenticaed () returns false or True in  - Django Login Authentication Decorator to  fromDjango.contrib.auth.decoratorsImportlogin_required +  - @login_required the defIndex (Request):Passdirectly loading the view, you can run the pre-authentication *  $ Django By default when a user accesses a page without logging in, it jumps to the login URL and saves the previous URL, and then jumps after loginPanax NotoginsengRequest Header: Location:/accounts/login/?next=/index/ -  theAbove is the default to jump to/accounts/login/so if you want to use the default must be the URL to change to/accounts/login/ + such a URL design is not convenient, it can be set in setting A  theLogin_url ='/login/'  #This is configured as a route for your project login page +  -  $  $ 'Django.contrib.auth.middleware.AuthenticationMiddleware', - No login without the session, the middleware will return an anonymous object, in order to resolve the call method does not error -  the Request.user is mainly used for the above middleware, into the middleware, - The main definition of a process_request () method, mostly done before the viewWuyi  the!!!! Request.user returns a user object or an anonymous object at the end of the
SummaryAn example of a registration
 fromDjango.contribImportAuth#Create a normal User: (registration example)defSignup (Request): Re_form_obj=Registerform ()ifRequest.method = ='POST': Re_form_obj=Registerform (Request. POST)ifRe_form_obj.is_valid ():#Validate the Form object, and verify that the user table is the field specified by the Auth table, such as the account secret can be used Auth.authenticate (username=,password=,) to username, Password is due to the default Auth table, where the user name and password field names are Username,password            #name = Form_obj.cleaned_data.get (' username ') # validation passed before getting to field            #paw = form_obj.cleaned_data.get (' password ')            #User.objects.create (USERNAME=NAME,PASSWORD=PWD) This is a plaintext password, which cannot be logged in, because the Django verification is verified by ciphertext, It is necessary to create the user in the encrypted form provided by Django, as follows            #User.objects.create_user (USERNAME=NAME,PASSWORD=PWD)            #orUser.objects.create_user (**form_obj.cleaned_data)#all key values are broken into the dictionary and written to the databaseextension: After the registration is completed, you can implement the automatic login through the background, the following code user_obj= Auth.authenticate (* *form_obj.cleaned_data) Auth.login (request,user_obj)#Create session            returnredirect'/index/')            #or the background to send JSON data to the foreground, reception through Ajax reception, rendering to the page, automatic login and a few seconds to jump

Django Framework-auth Components

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.