The way Django uses Ajax to register and activate accounts for email users

Source: Internet
Author: User
Tags button type
This article mainly introduced the Django through the Ajax to complete the mailbox user registration, activates the account the method, now shares to everybody, also gives everybody to make a reference. Come and see it together.

First, the image verification code

Django-simple-captcha Mating

1. In the Pycharm, file==== "settings====" project: program name = = = "Projects interpreter====" +==== "Search Django-simple-captcha Select 0.55 or more and install by installing the package button.

2. Add code in Project name/urls.py:

From django.urls import path,include......from users.views Import indexview......urlpatterns = [  ...    ] #配置验证码  Path (' captcha/', include (' Captcha.urls ')),  #首页url  path ("', Indexview.as_view (), name= ' index '),  ......]

Add a registration information to the 3.settings.py

Installed_apps = [    ...    ] Captcha ']

4. Open the terminal terminal execute the update database command:

Python manage.py Makemigrationspython manage.py Migrate

5. Create a new form.py file under the Users directory:

From Django Import formsfrom captcha.fields import Captchafield......class registerform (forms. Form): "" "  Verification of registration information"  "" ... Captcha=captchafield (error_messages={' invalid ': ' Captcha error '}) ...  

6. Add code in users/views.py:

From Users.form import Registerformclass Indexview (View): "" "First" ""  def Get (self,request):    register_form =registerform ()    return render (Request, ' index.html ', {' Register_form ': Register_form})

7. Display the verification code, the input box in the front page index.html

Html

<p class= "Modal Fade" id= "register" tabindex= "-1" role= "dialog" >  ......<!--modal box about registered content start-->   <p class= "Modal-body" > ...            <p><p style= "Display:inline-block;width:100px;text-align:center" ><b > Verification Code:</b></p> <!--verification code start-->      <p class= "Cap" >{{register_form.captcha}}</p><!--captcha end--></p>      {% Csrf_token%}    </form>     <p><p style= "margin-left:100px;background-color:orangered; Width:150px;text-align:center "><b></b></p></p>   </p><!-- The contents of the modal box about registration end--> ...  

Css

<style>  . cap{    Display:inline-block;    width:280px;    height:36px;  }  . Cap img{    float:right;  } </style>

JS is related to refresh verification code (jquery is required first)

$ (function () {    $ ('. Captcha '). css ({    ' cursor ': ' pointer '  });  /*# Ajax Refresh */    $ ('. Captcha '). Click (function () {      console.log (' click ');      $.getjson ("/captcha/refresh/", function (Result) {        $ ('. Captcha '). attr (' src ', result[' Image_url ']);        $ (' #id_captcha_0 '). Val (result[' key ')});})  

Second, Ajax mailbox registration

1. In the front end with the registered binding modal box code written:

Html

<p class= "Modal Fade" id= "register" tabindex= "-1" role= "Dialog" > ... <p class= "Modal-body" > <for M id= "Registerform" action= "#" method= "POST" > <p> <p class= "re-input" ><b> User name: &LT;/B&GT;&L t;/p> <input type= "text" name= "user" placeholder= "username" > <p class= "msg" ><b id= "User-msg"        ;</b></p> </p> <p> <p class= "re-input" ><b> mailbox:</b></p> <input type= "text" name= "email" placeholder= "Mailbox" > <p class= "msg" ><b id= "email-msg" >2222</b ></p> </p> <p> <p class= "re-input" ><b > Password:</b></p> &l T;input type= "password" name= "pwd" placeholder= "password (not less than 6 bits)" > <p class= "msg" ><b id= "pwd-msg" >222</b        ></p> </p> <p> <p class= "Re-input" ><b > Confirm Password:</b></p> <input type= "Password"Name=" Pwd2 "placeholder=" Confirm password "> <p class=" msg "><b id=" PWD-MSG2 ">22</b></p> </p > <p><p class= "re-input" ><b > Verification Code:</b></p> <p class= "Cap" >{{Register_fo Rm.captcha}}</p> <p class= "msg" ><b id= "captcha-msg" >2</b></p> </P> { % Csrf_token%} </form> <p><p style= "margin-left:100px;color:white;background-color:green;width:1 80px;text-align:center "><b id=" active-msg "></b></p></p> ... <button type=" button " class= "btn btn-primary" id= "REGISTERBTN" > Confirm registration </button> ...

Css

<style>  . cap{    Display:inline-block;    width:280px;    height:36px;  }  . Cap img{    float:right;  }  . re-input{    Display:inline-block;    width:100px;    Text-align:center  }  . msg{    margin-left:100px;    background-color:orangered;    width:180px;    Text-align:center  }</style>

The JS code associated with AJAX registration:

$ ("#registerbtn"). Click (function () {$.ajax ({cache:false, type: "POST", url: "{% url ' users:register '%}" , DataType: ' JSON ', data:$ (' #registerform '). Serialize (),//Find the submission form by ID, and turn the form into a string async:true,// Asynchronous is true, the process of Ajax commit, while you can do other operations Success:function (data) {//jquery3 Later, will be returned to the string format data automatic JSON parsing no longer use the Json.parse (DA        TA), otherwise the error will be on the console if (data.status) {$ (' #active-msg '). HTML (data.status);            } else{if (data.user) {username_msg=data.user.tostring ();          $ (' #user-msg '). html (' user name ' + username_msg);            } if (Data.email) {email_msg=data.email.tostring ();          $ (' #email-msg '). HTML (' mailbox ' + email_msg);            } if (data.pwd) {password_msg=data.pwd.tostring ();          $ (' #pwd-msg '). html (' password ' + password_msg);            } if (Data.captcha) {captcha_msg=data.captcha.tostring ();          $ (' #captcha-msg '). HTML (CAPTCHA_MSG);      }    Msg=data.__all__.tostring ();        $ (' #active-msg '). HTML (msg);  }      }    }); });

JS code to enhance the user interaction experience:

$ ("input"). Bind (' input PropertyChange ', function () {    $ (' #login-fail '). html (');    $ (' #user-msg '). html (');    $ (' #email-msg '). html (');    $ (' #pwd-msg '). html (');    $ (' #pwd-msg2 '). html (');    $ (' #captcha-msg '). html (');  });

2.users/form.py Code: (Field name to verify the name value of the front-end input box should be consistent!) )

From Django Import formsfrom captcha.fields import captchafieldfrom. Models import Userprofileclass registerform (forms. Form): "" "  Authentication of Registration Information" "  user = forms. Charfield (required=true, error_messages={' required ': ' User name cannot be empty. '})  Email=forms. Emailfield (required=true,error_messages={' Required ': ' Mailbox cannot be empty. '})  PWD = forms. Charfield (Required=true,             min_length=6,             error_messages={' required ': ' The password cannot be empty. ', ' min_length ': "At least 6 bits"})  PWD2 = forms. Charfield (Required=true,             min_length=6,             error_messages={' required ': ' The password cannot be empty. ', ' min_length ': "At least 6 bits"})  Captcha=captchafield (error_messages={' invalid ': ' Authenticode Error '}) def clean: ' '  verify that the    password is two times consistent '    p1= Self.cleaned_data.get (' pwd ')    p2=self.cleaned_data.get (' pwd2 ')    if p1!=p2:      raise forms. ValidationError (' Two input passwords inconsistent ')    else:      return Self.cleaned_data

Registration-related code in 3.users/views.py:

... from django.http import httpresponsefrom. Models import userprofile,shopprofilefrom Users.form Import Registerformfrom django.contrib.auth.hashers Import make_passwordimport jsonclass Registerview (View): "" "" "" "" Def Post (self, request): Register_form=registerform (Request. POST) if Register_form.is_valid (): User_name=request. Post.get (' user ', ') email=request. Post.get (' email ', ') pass_word=request. Post.get (' pwd ', ') U=userprofile.objects.filter (username=user_name). Count () E=userprofile.objects.filter (email=e Mail). Count () if u or E:return httpresponse (' {' Status ': ' The user name or mailbox is already occupied!        "} ') Else:user_profile=userprofile () User_profile.username=user_name User_profile.email=email        User_profile.password=make_password (Pass_word) user_profile.is_active=false User_profile.save () Return HttpResponse (' {' status ': ' Registration successful please go to mailbox activation! "} ') Msg=register_form.errors msg=json.dumps (msg) return HttpResponse (Msg 

4. Configure users/urls.py to register the route:

... from the. Views import registerview.....urlpatterns = [...]  Path (' register/', Registerview.as_view (), name= ' register '),  ...  ]

Third, the mailbox activation registered account:

1. Create a new data table to hold the mailbox Activation code:

Add code in users/models.py:

Class Emailverifyrecord (models. Model): "" "  Mailbox Activation Code" ""  code=models. Charfield (max_length=20,verbose_name= ' Verification Code ')  email=models. Emailfield (max_length=50,verbose_name= ' mailbox ')  send_type=models. Charfield (verbose_name= ' Verification code type ', choices= (' register ', ' Register '), (' Forget ', ' forgot Password '),                max_length=20)  send_time =models. Datetimefield (verbose_name= ' Send Time ', Default=datetime.now)  class Meta:    verbose_name= ' email Verification Code '    Verbose_ Name_plural=verbose_name  def __str__ (self):    return ' {0} ({1}) '. Format (self.code,self.email)

To register a data table in users/adminx.py:

... from. Models Import Emailverifyrecord......class emailverifyrecordadmin (object):  list_display = [' Code ', ' Email ', ' send_type ', ' send_time ']  search_fields = [' Code ', ' email ', ' send_type ']  list_filter = [' Code ', ' email ' , ' Send_type ', ' Send_time ']......xadmin.site.register (emailverifyrecord,emailverifyrecordadmin)

Open the terminal terminal execute the update database command:

Python manage.py Makemigrationspython manage.py Migrate

2. Script to write e-mail: Create a new utils/email_send.py in apps/users/

From random import randomfrom users.models import emailverifyrecordfrom django.core.mail import Send_mailfrom Xyw.settings Import email_fromdef random_str (randomlength=8): str= ' chars= ' AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789 ' Length=len (chars)-1 random=random () for I in range (  Randomlength): Str+=chars[random.randint (0,length)] return strdef send_register_email (email,send_type= ' register '): Email_record=emailverifyrecord () code=random_str (+) Email_record.code=code Email_record.email=email Email_ Record.send_type=send_type email_record.save () email_title= "email_body=" if send_type== ' register ': email_title= ' Snow NET registration Activation link ' email_body= ' please click on the link below to activate your account: http://127.0.0.1:8000/active/{0} '. Format (code) send_status=send_mail (e-mail    _title,email_body,email_from,[email]) If Send_status:pass elif send_type== ' Forget ': Email_title = ' Snow easy password reset link ' Email_body = ' Please click on the link below to reset your password: http://127.0.0.1:8000/reset/{0} '. Format (code) Send_status = Send_mAil (email_title, Email_body, Email_from, [email]) If Send_status:pass 

3. Append the configuration code for sending the message in settings.py:

email_host= ' smtp.sina.cn ' email_port=25email_host_user= ' xxxxxxxx@sina.cn ' #你的邮箱EMAIL_HOST_PASSWORD = ' ******** ' Email_use_tls=falseemail_from= ' xxxxxxx1@sina.cn ' #同样是你的邮箱, with the above are the sender mailbox # I use Sina, can also use other

4. Open the SMTP service of Sina mailbox, or you can't send email automatically, the steps are as follows:

Login Sina Mailbox = = = "Set zone = =" Client pop/imp/smtp==== "pop3/smtp service = =" Service Status: Open = = "Save

5. Add Activation function

Add the Activation Class Activeuserview (View) code in users/views.py:

... from. Models Import Emailverifyrecord......class Activeuserview (View): "" "  Activate Account" ""  def get (self, Request,active_code):    all_records=emailverifyrecord.objects.filter (code=active_code)    if all_records: For      record in all_records:        email=record.email        user=userprofile.objects.get (email=email)        User.is_ Active=true        user.save ()          return render (Request, ' index.html ')

6. In the users/views.py

Add code to the registration class Registerview (View) to send the activation message:

... from apps.utils.email_send import send_register_email......class Registerview (View):  "" "" "" "" " Def post (self, request):  ...  User_profile.save () #发送邮件代码start  send_register_email (email, ' register ') #发送邮件代码end  return HttpResponse (' {"Status": "Registration is successful please go to mailbox activation!" "}')

Add code to verify account activation for login LoginView (View):

Class LoginView (View): "" "  User Login" "  def Post (self,request):    user_name=request. Post.get ("username", "")    pass_word=request. Post.get ("pwd", "")    user=authenticate (username=user_name,password=pass_word)    if user is not none:# Verify that the account has activated start      if user.is_active:        login (request,user)        return HttpResponse (' {' status ': ' Success '} ')      else:        return HttpResponse (' {' status ': ' Fail ', ' msg ': ' Account Not activated '} ') #验证账户是否已经激活end    else:      return HttpResponse (' {' status ': ' Fail ', ' msg ': ' Username or password error '} ')

At this time to complete the use of mailbox registration and activation, many times, the activation of mail will be automatically put into the Trash box, and from the mail click on the activation link, you will also be prompted some warning message, you can say through the mailbox registration of various than by SMS registration, but ... Save money! ^_^

Related Article

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.