Django's Auth Module user authentication module

Source: Internet
Author: User

One, auth module

1) What is the Auth module? Login background using the account password, is the use of the Auth module created by the table

The auth module is a django-brought user authentication module: When we develop a website, it is unavoidable to design a 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. 

2) function of auth module

2.1) Import Auth module

 from Django.contrib import auth

2.2) method under the Auth module. Authenticate (). Authentication function

= Authenticate (username='usernamer', password='password')

The specific use is as follows

 fromdjango.contrib Import authdef auth_test (Request): Username= Request. post['username'] Password= Request. post['Password'] User= Auth.authenticate (Username=username, password=password)ifuser:print (user.username)returnHttpResponse ("Login Successful")    returnHttpResponse ("Logon Failure")
Authenticate use

2.3) Login (Request,user). Login function (after successful authentication)

 from django.contrib Import authdef auth_test (Request):     = Auth.authenticate (request,username='user2', password='user123456 '     # Authentication    print (user)    if user :        print (user.username)    # login Username        Auth.login (request,user)    return render (request,'auth_test.html  ')
Auth.login (Request,user)

Once logged in, the front end can also get the login user name

<body><div>{{Request.user}}</div></body>
{{Request.user}}

The front end can also be used to determine whether the request passed.

<body><div>{{request.user}}</div><div>{{request.user.is_authenticated}}</div> </body>
is_authenticated

2.4) Auth.logout (Request). User Exit method

def auth_test_logout (request):    auth.logout (Request)    return httpresponse ('  Exit success ')
auth.logout (Request)

Second, auth module expansion. For creating users, login adorners

1) New fields

1.1) Modify the configuration file settings.py

" app name. User Name Table "  "app01. UserInfo"  # Specify table
settings.py

1.2) Create a table that inherits Abstractuser. Overridable table Structure

 from django.contrib.auth.models Import Abstractuser class UserInfo (abstractuser):     = Models. Autofield (primary_key=True)    = models. Charfield (max_length=)
Abstractuser

2) Create user

def auth_test_creat_user (Request): # admin UserInfo.objects.create_superuser (username='USERSB1', password=123, email='[email protected]') # Ordinary user UserInfo.objects.create_user (username='USERSB2', password=123, email='[email protected]')    returnHttpResponse ('Success')
Creat_user

3.1) Login Adorner method one. The view function is preceded by a URL

@login_required (login_url='/auth_test_login/')   # operation def Auth_test_ after login Logout (Request):    auth.logout (Request)    return httpresponse (' exit successful  ')
@login_required

Login_url= '/auth_test_login/', no login jumps to the URL

3.2) Login Adorner method two. Settings Global Configuration

' /auth_test_login/ '
settings.py

You don't have to add a URL before the view function

@login_required   # operation can be done after login Def auth_test_logout (request):    auth.logout (Request    )return HttpResponse (' exit succeeded '
View Code

4) Check the password. Check_password (password).

The password returns true correctly, otherwise false is returned.

= User.check_password (' password ')if  tag:    print (" OK " )else:    print (" error ")
check_password (' password ')

5) Change the 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=") User.save ()
Set_password (password= ")

An example of a simple password change

@login_requireddef Set_password (Request): User=Request.user 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 correctifUser.check_password (old_password):ifNot new_password:err_msg='The new password cannot be empty'elif New_password!=repeat_password:err_msg='two times password inconsistency'            Else: User.set_password (New_password) user.save ()returnredirect"/login/")        Else: Err_msg='Original Password input error'content= {        'err_msg': Err_msg,}returnRender (Request,'set_password.html', content)
View Code

6) Properties of the user object

User Object properties: Username, Passwordis_staff: Whether users have administrative rights on the site. Is_active: Whether the user is allowed to log on and set to False can prevent users from logging on without deleting the user.
View Code

Iii. Summary (use of auth module)

configuration file: settings.py Auth_user_model="App01. UserInfo"# Create an Extended user table Login_url='/auth_test_login/'# Decorator's Jump Login URL create table: models.py fromdjango.contrib.auth.models Import Abstractuser # inherit AbstractuserclassUserInfo (abstractuser): Nid= Models. Autofield (primary_key=True) Telephone= Models. Charfield (max_length= +) View function method: views.py auth.authenticate (Request,username='User2', password='user123456'# Authentication Auth.login (request,user) # login print (request.user) # property, user name Request.user.is_authentica    Ted # property to determine if the request was made by @login_required # adorner UserInfo.objects.create_superuser () # Create Super Admin        UserInfo.objects.create_user () # Create normal admin check_password (password) # Check password Set_password (password) # Modify the password front-end file: The request requests the body contains the user object backend properties, the front end can also get {{Request.user}} {{request.user.is_authenticated}}< /c7>

Django's Auth Module user authentication module

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.