Python3 Development of Advanced-django framework with self-authentication function Auth module and basic operation of user object

Source: Internet
Author: User
Tags session id

Read Catalogue

    1. Auth Module
    2. User Object
    3. Certification Advanced

One, auth module
From Django.contrib Import Auth

There are a number of methods available in Django.contrib.auth, which are mainly about three of them:

Authenticate ()

Provide user authentication, that is, verify the user name and password is correct, generally need username password two keyword parameters

If the authentication information is 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.

user = Auth.authenticate (username=username, password=pwd)        if  User:#  Built-in Login method #  1. Generate session data, save user_id and then write SessionID to Cookie#  When every subsequent request comes in, The Process_request method in Authenticationmiddleware  takes the user_id and then takes the user object and adds it to the Request.user attribute-- > request.user = user#  Subsequent we can get the current login user object via Request.user
Login (httprequest, user)

The function accepts a HttpRequest object, and an authenticated user object

This function uses the Django session framework to attach information such as session ID to an authenticated user.

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 ' invalid login ' error message.    ...
Logout (Request) logoff user  
 from Import Logout    def Logout_view (Request):  logout (Request)  #  Call Auth built-in logout method

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.

The user object's is_authenticated ()

Requirements:

    1. Users can access certain pages after landing,
    2. If the user is not logged in to access the page, go directly to the login page
    3. When the user completes the login in the login interface of the jump, automatic access jumps to the previously visited address

Method 1:

def my_view (Request):  if not request.user.is_authenticated ():    return redirect ('%s?next=%s '% (settings. Login_url, Request.path))

Method 2:

Django has designed a decorator for this case: Login_requierd ()

From django.contrib.auth.decorators 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/' (this value can be modified through Login_url in the settings.py file).

and passes the absolute path of the current access URL (which is redirected to the path after successful login).

Second, the User object

User Object properties: Username, password (required) password save to database with hashing algorithm

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 not delete users to prevent users from logging

Is_authenticated ()

If it is a real User object, the return value is constant true. Used to check if the user has passed the authentication.
Certification does not imply that the user has any permissions, and this method does not even check that the user is active, only that the user has successfully passed the authentication.

This method is very important, in the background with request.user.is_authenticated () to determine whether the user is logged in, if True can be displayed to the foreground request.user.name

Create user

To create a user using the Create_user helper function:

From django.contrib.auth.models Import useruser = User.objects.create_user (username= ", password=", email= ")
Check_password (password)

When the user needs to change the password, first let it enter the original password, if the given value passed the password check, return True

Change Password

Use Set_password () to change the password

user = User.objects.get (username=") user.set_password (Password="#  Go to database to change password #
Simple example
@login_requireddefSet_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 correct        ifUser.check_password (old_password):if  notnew_password:err_msg='The new password cannot be empty'            elifNew_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)
Modify Password Example

Third, certification advanced

This built-in Auth_User table works so well, but I can't use 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 one of our own ORM classes by inheriting the corresponding class of the built-in Auth_User table:

 from Import Abstractuser class 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 tell Django in settings.py that I am now using my newly defined userinfo table to authenticate the user. The wording is as follows:

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

How do I set the default login page?

Login_url= "Default Page"

Python3 Development of Advanced-django framework with self-authentication function Auth module and basic operation of user object

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.