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.
Auth Module
From Django.contrib 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.auth import Authenticate, login def my_view (request): username = Request. post[' username '] password = Request. post[' password '] user = Authenticate (request, 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)
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 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): if 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:
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/' 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_url = '/login/' # This is configured as a route for 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:
From django.contrib.auth.models Import useruser = User.objects.create_user (username= ' user name ', password= ' password ', email= ' mailbox ', ... )
Create_superuser ()
Auth provides a way to create a new super-user that needs to provide the necessary parameters (username, password), and so on.
Usage:
From django.contrib.auth.models 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.
Note: Be sure to invoke the Save method of the User Object!!!
Usage:
User.set_password (password= ") User.save ()
A simple example of a password change feature
@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 if the old password is correct if User.check_password (old_password): if not new_password: err_msg = ' New password cannot be empty ' elif new_password! = Repeat_password: err_msg = ' two times password 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)
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.
Extending 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.
From django.contrib.auth.models import Abstractuserclass UserInfo (abstractuser): "" " User Information table" " nid = Models. Autofield (primary_key=true) phone = 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, and you need to set Auth_user_model = "app name when you inherit it. 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.
Django Feature-auto module