Django Authentication System

Source: Internet
Author: User
Django built-in user authentication

When developing a website, we inevitably need to design and implement the website's user system. At this point, we need to implement functions such as user registration, user logon, user authentication, logout, and password modification, which is really a hassle.

Django, as the ultimate framework of perfectionist, will certainly think of these pain points of users. It has built-in powerful user authentication system-auth, which uses the auth_user table by default to store user data.

Auth Module
from django.contrib import auth

Auth provides many practical methods:

Authenticate ()

The user authentication function is provided to verify whether the user name and password are correct. Generally, two keyword parameters are required: username and password.

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

Authenticate () sets an attribute on the user object to identify that the user has been authenticated by the backend, and this information is required during subsequent login.

Usage:

user = authenticate(username=‘theuser‘,password=‘thepassword‘)
Login (httprequest, user)

This function accepts an httprequest object and an authenticated user object.

This function enables a user to log on. It generates session data for the user at the backend.

Usage:

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)

This function accepts an httprequest object and has no return value.

When this function is called, all session information of the current request is cleared. This function does not return an error even if the user does not log on.

Usage:

from django.contrib.auth import logout   def logout_view(request):  logout(request)  # Redirect to a success page.
Is_authenticated ()

Used to determine whether the current request has been authenticated.

Usage:

def my_view(request):  if not request.user.is_authenticated():    return redirect(‘%s?next=%s‘ % (settings.LOGIN_URL, request.path))
Login_requierd ()

Auth provides us with a decorator tool to quickly add login verification to a view.

Usage:

from django.contrib.auth.decorators import login_required      @login_requireddef my_view(request):  ...

If the user does not log on, the default Django login URL '/accounts/login/' will be redirected and the absolute path of the current access URL will be passed (after successful login, it will be redirected to this path ).

If you need to customize the logon URL, You need to modify it through login_url in the settings. py file.

Example:

Login_url = '/login/' # configure the route entry on the login page of your project.
Create_user ()

Auth provides a method for creating a new user. You need to provide necessary parameters (username, password.

Usage:

From Django. contrib. Auth. Models import useruser = user. Objects. create_user (username = 'username', password = 'Password', email = 'mailbox ',...)
Create_superuser ()

Auth provides a method to create a new super user, and requires necessary parameters (username, password.

Usage:

From Django. contrib. Auth. Models import useruser = user. Objects. create_superuser (username = 'username', password = 'Password', email = 'mailbox ',...)
Check_password (password)

Auth provides a method to check whether the password is correct. The password of the currently requested user must be provided.

If the password is correct, true is returned. 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.

Note: The save method of the user object must be called after setting !!!

Usage:

user.set_password(password=‘‘)user.save()

A simple example of the password change function

@ Login_requireddef set_password (request): User = request. user err_msg = ''if request. method = 'post': old_password = request. post. get ('old _ password', '') new_password = request. post. get ('new _ password', '') repeat_password = request. post. get ('Repeat _ password', '') # Check whether the old password is correct if user. check_password (old_password): If not new_password: err_msg = 'new password cannot be blank 'Elif new_password! = Repeat_password: err_msg = 'two passwords are inconsistent. 'else: user. set_password (new_password) user. save () return redirect ("/login/") else: err_msg = 'original password input error 'content = {'err _ MSG': err_msg,} return render (request, 'set_password.html ', content)
Modify the attributes of the user object in the password example

User object attributes: username, password

Is_staff: whether the user has the permission to manage the website.

Is_active: whether to allow user logon. If this parameter is set to false, user logon is disabled without deleting a user.

Extended default auth_user table

This built-in authentication system is so easy to use, but the auth_user table fields are fixed and I cannot use them directly in the project!

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

If you are smart, you may want to create another table and associate it with the built-in auth_user table through one-to-one. Although this can meet the requirements, is there a better way to implement it?

The answer is yes, of course.

We can define a model class by inheriting the built-in abstractuser class.

In this way, you can design user tables flexibly according to project requirements and use the powerful Django authentication system.

From Django. contrib. auth. models import abstractuserclass userinfo (abstractuser): "User Info table" nid = models. autofield (primary_key = true) Phone = models. charfield (max_length = 11, null = true, unique = true) def _ STR _ (Self): return self. username

Note:

After the built-in auth_user table is extended in the above method, you must tell Django in settings. py that I am using my new userinfo table for user authentication. The statement is as follows:

# Reference the user table that comes with Django. You need to set auth_user_model = "app name. userinfo" when using inheritance"

Note again:

Once we specify the table used by the new authentication system, we need to re-create the table in the database, instead of continuing to use the original default auth_user table.

 

Django 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.