User Registration and email verification methods in Django, django User Registration

Source: Internet
Author: User

User Registration and email verification methods in Django, django User Registration

This article describes how to register an article using Django. First, let's talk about the overall logic:

• Process user registration data,

• Generate token, generate verification URL,

• Send verification emails,

• The user logs on to the website for verification,

• Verification processing.

Procedure:

1. Add a user

In the User table that comes with Django, there is an is_active field. The default value is True. That is, you can log on after entering the form for submission. Here, we first set the is_acitve field to False, that is, the login can be normal only after subsequent email verification.

Some code:

if request.method == 'POST':form = CustomUserCreationForm(request.POST)if form.is_valid():cd = form.cleaned_data#new_user = form.save()username,password,email = cd['username'],cd['password1'],cd['email']user = User.objects.create(username=username, password=password, email=email, is_active=False)user.set_password(password)user.save() 

After submission, a record is added to the database, but the is_acitve field is False, which is not a valid user.

2. Email Verification

There are two main steps for email verification: one is the production certificate token, that is, encryption, and the other is to process the verification link.

1) generate token

Previously I used a simple base64 encryption and decryption method, but after all it is too simple, and later saw the Flask user authentication article (http://python.jobbole.com/81410/), it uses the itsdangerous serialization method, in fact, the Flask session uses itsdangerous serialization. An important reason for using it is that it comes with a timestamp, And the serialization method is much more powerful than simply using base64.

Code:

from itsdangerous import URLSafeTimedSerializer as utsrimport base64import re

Class Token ():

def __init__(self,security_key):self.security_key = security_keyself.salt = base64.encodestring(security_key)def generate_validate_token(self,username):serializer = utsr(self.security_key)return serializer.dumps(username,self.salt)def confirm_validate_token(self,token,expiration=3600):serializer = utsr(self.security_key)return serializer.loads(token,salt=self.salt,max_age=expiration) 

Security_key is the SECRET_KEY set in settings. py, and salt is the base64-encrypted SECRET_KEY. The generate_validate_token function generates a token during user registration through URLSafeTimedSerializer. The user name is coded in the token. After a token is generated, the verification link with a token is sent to the registered email address. In the confirm_validate_token function, as long as the token has not expired, it will return a user name with an expiration time of 3600 seconds.

Function Code for sending emails:

Token = token_confirm.generate_validate_token (username) # active_key = base64.encodestring (username) # send email to the register emailmessage = "\ n ". join ([U' {0}, welcome to join my blog '. format (username), U' visit this link to complete user verification :','/'. join ([DOMAIN, 'account/activate', token]) send_mail (u'registration user verification information', message, None, [email])

2) process email Verification

Is the view function corresponding to the verification link. The main purpose of this function is to update the is_active field of the User in the User table to True.

def active_user(request,token):username = token_confirm.confirm_validate_token(token)user = User.objects.get(username=username)user.is_active = Trueuser.save() 

Here we will talk about url settings. The token generated by itsdangerous is random and regular because it is composed of three parts separated by dots. Similar: Imhibm4i. Cg-UAQ.n7ZI2N9kUZ1eOcfBtxlMOdOYYE0. It is random because each part of the content may not only contain letters and numbers, but may also contain connectors -,_. Therefore, the url should be: url (R' ^ account/activate /(? P <token> \ w +. [-_ \ w] * \ w +. [-_ \ w] * \ w +)/$ ', 'blog. views. active_user ', name = 'Active _ user ')

After the above operations, the user can use the user name just registered to log on.

Paste the complete code:

from utils.token import Tokenfrom django.core.mail import send_mailfrom .forms import UserLoginForm,CustomUserCreationFormtoken_confirm = Token(SECRET_KEY)

Def Register (request ):

If request. method = 'post': form = CustomUserCreationForm (request. POST) if form. is_valid (): cd = form. cleaned_data # new_user = form. save () username, password, email = cd ['username'], cd ['password1 '], cd ['email'] user = User. objects. create (username = username, password = password, email = email, is_active = False) user. set_password (password) user. save () token = token_confirm.generate_validate_token (username) # active_key = Base64.encodestring (username) # send email to the register emailmessage = "\ n ". join ([U' {0}, welcome to join my blog '. format (username), U' visit this link to complete user verification :','/'. join ([DOMAIN, 'account/activate', token]) send_mail (u'register user authentication information', message, None, [cd ['email ']) # user = auth. authenticate (username = username, password = password) # auth. login (request, user) return HttpResponse (u "Please log on to the registered mailbox to verify the user, valid for 1 hour. ") Else: form = CustomUserCreationForm () return render(request,'register.html ', {'form': form}) def active_user (request, token ): "the view function is used to accomplish the user register confirm, only after input the linkthat sent to the register email, user can login the site normally.: param request: param activate_key: the parten is gotten by encrypting username when user register: return: "" try: usernam E = token_confirm.confirm_validate_token (token) failed T: return HttpResponse (u'sorry, verification link expired ') try: user = User. objects. get (username = username) failed T User. doesNotExist: return HttpResponse (U' sorry, the user you have verified does not exist. Please register again ') user. is_active = Trueuser. save () confirm = U' is verified successfully. Please log on. 'Return HttpResponseRedirect ('/account/login', {'Confirm': confirm })

The above is a small Editor to introduce you to the method of user registration and email verification in Django, I hope to help you!

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.