When building websites and web applications, user login and management are essential for almost every website. Today, we will learn about the following django user module from an instance. This document does not extend the user.
It mainly uses native modules.
1. User Module basics:
Import data to your iew before using the user. It is equivalent to the models we have written. However, this is the models provided by the system.
From django. contrib. auth. models import User # import user Module
1.1User object attribute User object attribute: username, password (required) password is saved to the database by hash algorithm
Email, last_login, date_joined (literally)
Is_staff; whether the user has the permission to manage the website.
Is_active: whether to allow user logon. Set this parameter to ''false''. You do not need to delete a user to disable user logon.
1.2 User object Method
Is_authenticated (): If it is a real User object, the return value is always True. Used to check whether the user has passed the authentication. Passing authentication does not mean that the user has any permissions or even does not check whether the user is in the active state. This only indicates that the user has successfully passed the authentication.
This method is very important. In the background, use request. user. is_authenticated () to determine whether the user has logged on. If it is true, the request. user. name can be displayed to the foreground.
: Set_password (passwd)
This method is used to change the password. First Use user = User. objects. get (username = '')
User. set_password (passeord = '')
User. save
Check_password (passwd)
When a user needs to change the password, he must first input the original password. If the given string passes the password check, True is returned.
Email_user (subj, msg)
Send an email to the user and use the settings of DEFAULT_FROM_EMAIL as the sender. You can also use the 3rd from_email parameter to overwrite the settings.
1.3; create a User
Use the create_user auxiliary function to create a user:
From django. contrib. auth. models import User
User = User. objects. create_user (username = '', password ='', email = '')
User. save. Note that this is not save ()!
1.4. logon and authentication
Django provides two functions in django. contrib. auth to handle these tasks-authenticate () and login ()
Authenticate (): the user name and password provided for authentication. Use the authenticate () function. It accepts two parameters, username and password, and returns a User object when the password pair is valid. If the given password is invalid, the authenticate () function returns None.
Login (): This function accepts an HttpRequest object and a User object as parameters, and uses the Django session framework to save the User ID in this session.
From django. contrib import auth
User = auth. authenticate (username = username, password = password)
If user:
Auth. login (request, user)
1. 5. logout and redirection
Log out of logout (). This function accepts an HttpRequest object as a parameter and does not return a value.
Auth. logout (request)
Redirection: HttpResponseRedirect (). This function mainly implements url redirection.
After logging on and logging out, redirect to the specified url. This function can adopt url hard encoding.
Return HttpResponseRedirect ('/sbook/sb_show ')
2. Implement User Registration and login
Based on the above basic knowledge, we have learned how to create and update a user. Next we will use an instance for user registration and login.
The mvc model of the case has already provided the model, so we only need to implement iew and template. In view. py, you can control registration and logon.
First look at the Code in the following view
def alogin(request): errors= [] account=None password=None if request.method == 'POST' : if not request.POST.get('account'): errors.append('Please Enter account') else: account = request.POST.get('account') if not request.POST.get('password'): errors.append('Please Enter password') else: password= request.POST.get('password') if account is not None and password is not None : user = authenticate(username=account,password=password) if user is not None: if user.is_active: login(request,user) return HttpResponseRedirect('/index') else: errors.append('disabled account') else : errors.append('invaild user') return render_to_response('account/login.html', {'errors': errors})def register(request): errors= [] account=None password=None password2=None email=None CompareFlag=False if request.method == 'POST': if not request.POST.get('account'): errors.append('Please Enter account') else: account = request.POST.get('account') if not request.POST.get('password'): errors.append('Please Enter password') else: password= request.POST.get('password') if not request.POST.get('password2'): errors.append('Please Enter password2') else: password2= request.POST.get('password2') if not request.POST.get('email'): errors.append('Please Enter email') else: email= request.POST.get('email') if password is not None and password2 is not None: if password == password2: CompareFlag = True else : errors.append('password2 is diff password ') if account is not None and password is not None and password2 is not None and email is not None and CompareFlag : user=User.objects.create_user(account,email,password) user.is_active=True user.save return HttpResponseRedirect('/account/login') return render_to_response('account/register.html', {'errors': errors})def alogout(request): logout(request) return HttpResponseRedirect('/index')
From the above Code, we create a form in the template.
Create an account directory under templates. Create login.html
Welcome login Account Login
{% if errors %}
{% for error in errors %} Please correct the error: {{error}} below.
{% endfor %} {% endif %} Create register.html in the same format
Welcome Register New Account {% if errors %} {% for error in errors %} Please correct the error: {{error}} below.
{% endfor %} {% endif %}
Next, the view and template are created, and there is only the uring relationship between the bed urls.
url(r'^account/login/$', alogin), url(r'^account/register/$', register), url(r'^account/logout/$', alogout),
So far, you can see the effect on your browser after registering and logging on.