Home Backend Development Python Tutorial How to complete email user registration and account activation through ajax in django

How to complete email user registration and account activation through ajax in django

Apr 17, 2018 am 11:43 AM
ajax django Mail

This article mainly introduces how Django completes email user registration and account activation through ajax. Now I share it with you and give it as a reference. Let’s take a look together

1. Image verification code

django-simple-captcha configurationSetting

1. In pycharm, File====》Settings====》Project:Project name====》Project Interpreter====》 ====》Search django-simple-captcha》Select 0.55 The above version, then click the install package button to install

2. Add the 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'),

  ......
]
Copy after login

3.settings Add a registration information in .py

INSTALLED_APPS = [

    ......
  
  'captcha'
]
Copy after login

4. Open the Terminal and execute the update database command:

python manage.py makemigrations
python manage.py migrate
Copy after login
Copy after login

5. Create a new form.py file in the users directory:

from django import forms
from captcha.fields import CaptchaField
......


class RegisterForm(forms.Form):
  """注册信息的验证"""

  ......

  captcha=CaptchaField(error_messages={'invalid':'验证码错误'})

  ......
Copy after login

6. Add code to users/views.py:

from users.form import RegisterForm


class IndexView(View):
  """首页"""
  def get(self,request):
    register_form=RegisterForm()
    return render(request,'index.html',{'register_form':register_form})
Copy after login

7. Display the verification code and input box in the front-end homepage index.html

html

<p class="modal fade" id="register" tabindex="-1" role="dialog">

  ......

<!--模态框中关于注册的内容start-->
   <p class="modal-body">
    ......
      
      <P><p style="display: inline-block;width:100px;text-align: center"><b >验证码:</b></p>

<!--验证码start-->

      <p class="cap">{{ register_form.captcha }}</p>

<!--验证码end-->

</P>
      {% csrf_token %}
    </form>
     <p><p style="margin-left: 100px;background-color: orangered;width:150px;text-align: center"><b></b></p></p>
   </p>

<!--模态框中关于注册的内容end-->

  ......
Copy after login

css

<style>
  .cap{
    display: inline-block;
    width: 280px;
    height: 36px;
  }
  .cap img{
    float: right;
  }
</style>
Copy after login

js is related to refreshing the verification code (need to introduce jQuery first)

$(function(){
    $(&#39;.captcha&#39;).css({
    &#39;cursor&#39;: &#39;pointer&#39;
  });
  /*# ajax 刷新*/
    $(&#39;.captcha&#39;).click(function(){
      console.log(&#39;click&#39;);
      $.getJSON("/captcha/refresh/",function(result){
        $(&#39;.captcha&#39;).attr(&#39;src&#39;, result[&#39;image_url&#39;]);
        $(&#39;#id_captcha_0&#39;).val(result[&#39;key&#39;])
      });
    });
  })
Copy after login

2. Ajax email registration

1. The modal box code bound to the registration on the front end is written as:

html

<p class="modal fade" id="register" tabindex="-1" role="dialog">

 ......
   
   <p class="modal-body">
    <form id="registerform" action="#" method="post">
      <p>
        <p class="re-input"><b>用户名:</b></p>
        <input type="text" name="user" placeholder="用户名">
        <p class="msg"><b id="user-msg"></b></p>
      </p>
      <p>
        <p class="re-input"><b>邮箱:</b></p>
        <input type="text" name="email" placeholder="邮箱">
        <p class="msg"><b id="email-msg">2222</b></p>
      </p>
      <p>
        <p class="re-input"><b >密码:</b></p>
        <input type="password" name="pwd" placeholder="密码(不少于6位)">
        <p class="msg"><b id="pwd-msg">222</b></p>
      </p>
      <p>
        <p class="re-input"><b >确认密码:</b></p>
        <input type="password" name="pwd2" placeholder="确认密码">
        <p class="msg"><b id="pwd-msg2">22</b></p>
      </p>
      <P><p class="re-input"><b >验证码:</b></p>
        <p class="cap">{{ register_form.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:180px;text-align: center"><b id="active-msg"></b></p></p>

   ......

    <button type="button" class="btn btn-primary" id="registerbtn">确认注册</button>

   ......
Copy after login

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>
Copy after login

js code related to ajax registration :

$("#registerbtn").click(function() {
    $.ajax({
      cache:false,
      type:"POST",
      url:"{% url &#39;users:register&#39; %}",
      dataType:&#39;json&#39;,
      data:$(&#39;#registerform&#39;).serialize(),
      //通过id找到提交form表单,并将表单转成字符串
      async:true,
      //异步为真,ajax提交的过程中,同时可以做其他的操作
      success:function (data) {
        //jquery3以后,会将回传过来的字符串格式的data自动json解析不用再使用一遍JSON.parse(data)了,不然反而会在控制台报错
        if(data.status){
          $(&#39;#active-msg&#39;).html(data.status);

        } else{
          if(data.user){
            username_msg=data.user.toString();
            $(&#39;#user-msg&#39;).html(&#39;用户名&#39;+ username_msg);
          }
          if(data.email){
            email_msg=data.email.toString();
            $(&#39;#email-msg&#39;).html(&#39;邮箱&#39;+ email_msg);
          }
          if(data.pwd){
            password_msg=data.pwd.toString();
            $(&#39;#pwd-msg&#39;).html(&#39;密码&#39;+ password_msg);
          }
          if(data.captcha){
            captcha_msg=data.captcha.toString();
            $(&#39;#captcha-msg&#39;).html(captcha_msg);
          }
          msg=data.__all__.toString();
          $(&#39;#active-msg&#39;).html(msg);

        }
      }
    });
  });
Copy after login

JS code to improve user interaction experience:

$("input").bind(&#39;input propertychange&#39;, function() {
    $(&#39;#login-fail&#39;).html(&#39;&#39;);
    $(&#39;#user-msg&#39;).html(&#39;&#39;);
    $(&#39;#email-msg&#39;).html(&#39;&#39;);
    $(&#39;#pwd-msg&#39;).html(&#39;&#39;);
    $(&#39;#pwd-msg2&#39;).html(&#39;&#39;);
    $(&#39;#captcha-msg&#39;).html(&#39;&#39;);
  });
Copy after login

2.users /form.py code: (The field name to be verified must be consistent with the name value of the front-end input box!)

from django import forms
from captcha.fields import CaptchaField
from .models import UserProfile


class RegisterForm(forms.Form):
  """注册信息的验证"""
  user = forms.CharField(required=True, error_messages={&#39;required&#39;: &#39;用户名不能为空.&#39;})
  email=forms.EmailField(required=True,error_messages={&#39;required&#39;: &#39;邮箱不能为空.&#39;})
  pwd = forms.CharField(required=True,
             min_length=6,
             error_messages={&#39;required&#39;: &#39;密码不能为空.&#39;, &#39;min_length&#39;: "至少6位"})
  pwd2 = forms.CharField(required=True,
             min_length=6,
             error_messages={&#39;required&#39;: &#39;密码不能为空.&#39;, &#39;min_length&#39;: "至少6位"})
  captcha=CaptchaField(error_messages={&#39;invalid&#39;:&#39;验证码错误&#39;})

  def clean(self):
    &#39;&#39;&#39;验证两次密码是否一致&#39;&#39;&#39;
    p1=self.cleaned_data.get(&#39;pwd&#39;)
    p2=self.cleaned_data.get(&#39;pwd2&#39;)
    if p1!=p2:
      raise forms.ValidationError(&#39;两次输入密码不一致&#39;)
    else:
      return self.cleaned_data
Copy after login

3.users/views.py Code related to registration:

......

from django.http import HttpResponse
from .models import UserProfile,ShopProfile
from users.form import RegisterForm
from django.contrib.auth.hashers import make_password
import json



class RegisterView(View):
  """邮箱注册"""
  def post(self, request):
    register_form=RegisterForm(request.POST)
    if register_form.is_valid():
      user_name=request.POST.get(&#39;user&#39;,&#39;&#39;)
      email=request.POST.get(&#39;email&#39;,&#39;&#39;)
      pass_word=request.POST.get(&#39;pwd&#39;,&#39;&#39;)
      u=UserProfile.objects.filter(username=user_name).count()
      e=UserProfile.objects.filter(email=email).count()
      if u or e:
        return HttpResponse(&#39;{"status":"该用户名或邮箱已被占用!"}&#39;)
      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(&#39;{"status":"注册成功请去邮箱激活!"}&#39;)
    msg=register_form.errors
    msg=json.dumps(msg)
    return HttpResponse(msg)
Copy after login

4. Configure users/urls.py registration route:

......

from .views import RegisterView
.....

urlpatterns = [

  ......

  path(&#39;register/&#39;,RegisterView.as_view(),name=&#39;register&#39;),

  ......
  ]
Copy after login

3. E-mail activation for registered accounts:

1. Create a new data table to store the e-mail activation code:

Add code in users/models.py:

class EmailVerifyRecord(models.Model):
  """邮箱激活码"""
  code=models.CharField(max_length=20,verbose_name=&#39;验证码&#39;)
  email=models.EmailField(max_length=50,verbose_name=&#39;邮箱&#39;)
  send_type=models.CharField(verbose_name=&#39;验证码类型&#39;,choices=((&#39;register&#39;,&#39;注册&#39;),(&#39;forget&#39;,&#39;忘记密码&#39;)),
                max_length=20)
  send_time=models.DateTimeField(verbose_name=&#39;发送时间&#39;,default=datetime.now)
  class Meta:
    verbose_name=&#39;邮箱验证码&#39;
    verbose_name_plural=verbose_name
  def __str__(self):
    return &#39;{0}({1})&#39;.format(self.code,self.email)
Copy after login

Register the data table in users/adminx.py:

......

from .models import EmailVerifyRecord

......

class EmailVerifyRecordAdmin(object):
  list_display = [&#39;code&#39;, &#39;email&#39;, &#39;send_type&#39;, &#39;send_time&#39;]
  search_fields = [&#39;code&#39;, &#39;email&#39;, &#39;send_type&#39;]
  list_filter = [&#39;code&#39;, &#39;email&#39;, &#39;send_type&#39;, &#39;send_time&#39;]

......

xadmin.site.register(EmailVerifyRecord,EmailVerifyRecordAdmin)
Copy after login

Open Terminal and execute the update database command:

python manage.py makemigrations
python manage.py migrate
Copy after login
Copy after login

2. Write a script for sending emails: Create new utils/email_send.py in apps/users/

from random import Random
from users.models import EmailVerifyRecord
from django.core.mail import send_mail
from xyw.settings import EMAIL_FROM


def random_str(randomlength=8):
  str=&#39;&#39;
  chars=&#39;AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789&#39;
  length=len(chars)-1
  random=Random()
  for i in range(randomlength):
    str+=chars[random.randint(0,length)]
  return str

def send_register_email(email,send_type=&#39;register&#39;):
  email_record=EmailVerifyRecord()
  code=random_str(16)
  email_record.code=code
  email_record.email=email
  email_record.send_type=send_type
  email_record.save()

  email_title=&#39;&#39;
  email_body=&#39;&#39;

  if send_type==&#39;register&#39;:
    email_title=&#39;雪易网注册激活链接&#39;
    email_body=&#39;请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}&#39;.format(code)

    send_status=send_mail(email_title,email_body,EMAIL_FROM,[email])
    if send_status:
      pass
  elif send_type==&#39;forget&#39;:
    email_title = &#39;雪易密码重置链接&#39;
    email_body = &#39;请点击下面的链接重置你的密码:http://127.0.0.1:8000/reset/{0}&#39;.format(code)

    send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
    if send_status:
      pass
Copy after login

3. Add the configuration code for sending emails in settings.py:

EMAIL_HOST=&#39;smtp.sina.cn&#39;
EMAIL_PORT=25
EMAIL_HOST_USER=&#39;xxxxxxxx@sina.cn&#39; #你的邮箱
EMAIL_HOST_PASSWORD=&#39;********&#39;
EMAIL_USE_TLS=False
EMAIL_FROM=&#39;xxxxxxx1@sina.cn&#39; #同样是你的邮箱,跟上面都是发信者邮箱
#我用的新浪的,也可以用别的
Copy after login

4. Enable the SMTP service of Sina Mailbox, otherwise it will not be able to send emails automatically. The steps are as follows:

Log in to Sina Mailbox====》Settings Area== ==》Client pop/imp/smtp====》Pop3/SMTP service====》Service status: on====》Save

5. Add activation function

Add activation class ActiveUserView(View) code in users/views.py:

......

from .models import EmailVerifyRecord

......

class ActiveUserView(View):
  """激活账户"""
  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,&#39;index.html&#39;)
Copy after login

6. In users/views.py

Add the code for sending activation emails to the registration class RegisterView(View):

......
from apps.utils.email_send import send_register_email


......

class RegisterView(View):
  """邮箱注册"""
  def post(self, request):
  ......
  user_profile.save()

#发送邮件代码start
  send_register_email(email,&#39;register&#39;)
#发送邮件代码end

  return HttpResponse(&#39;{"status":"注册成功请去邮箱激活!"}&#39;)
Copy after login

Add the code to verify whether the account is activated or not for the login LoginView(View):

class LoginView(View):
  """用户登录"""
  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:

#验证账户是否已经激活start
      if user.is_active:
        login(request,user)
        return HttpResponse(&#39;{"status":"success"}&#39;)
      else:
        return HttpResponse(&#39;{"status":"fail","msg":"账户未激活"}&#39;)

#验证账户是否已经激活end

    else:
      return HttpResponse(&#39;{"status":"fail","msg":"用户名或密码错误"}&#39;)
Copy after login

Now you have completed the registration and activation by email. Many times, the activation email will be automatically put into the trash by the email, and when you click the activation link from the email, You will also be prompted with some warning messages. It can be said that registering through email is not as good as registering through SMS, but... you save money! ^_^

Related recommendations:

Detailed explanation of Django’s auth module (user authentication)

The above is the detailed content of How to complete email user registration and account activation through ajax in django. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

okx Ouyi official website registration portal 2025 okx Ouyi official website registration portal 2025 Mar 04, 2025 pm 11:45 PM

OKX Ouyi is a leading cryptocurrency trading platform. This article will provide detailed steps to guide you on how to register an OKX Ouyi official website account. You will learn how to access the official website, choose the registration method, fill in the necessary information, and complete the registration process. The article also contains information about precautions, such as the importance of using real personal information and setting a strong password.

Sesame Open Door Exchange Web Page Login Latest version gateio official website entrance Sesame Open Door Exchange Web Page Login Latest version gateio official website entrance Mar 04, 2025 pm 11:48 PM

A detailed introduction to the login operation of the Sesame Open Exchange web version, including login steps and password recovery process. It also provides solutions to common problems such as login failure, unable to open the page, and unable to receive verification codes to help you log in to the platform smoothly.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

How to register and download the latest app on Bitget official website How to register and download the latest app on Bitget official website Mar 05, 2025 am 07:54 AM

This guide provides detailed download and installation steps for the official Bitget Exchange app, suitable for Android and iOS systems. The guide integrates information from multiple authoritative sources, including the official website, the App Store, and Google Play, and emphasizes considerations during download and account management. Users can download the app from official channels, including app store, official website APK download and official website jump, and complete registration, identity verification and security settings. In addition, the guide covers frequently asked questions and considerations, such as

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

gate.io official login web version Sesame Open Door Trading Platform web version login web version gate.io official login web version Sesame Open Door Trading Platform web version login web version Mar 04, 2025 pm 04:33 PM

The login method of the Sesame Open Door Trading Platform is convenient. Users only need to visit their official website (please search for the domain name yourself), enter the registered email/mobile phone number and password to log in. The platform may enable security verification mechanisms such as 2FA to ensure account security.

What are the routines of digital currency contracts? How to play a digital currency contract? What are the routines of digital currency contracts? How to play a digital currency contract? Mar 03, 2025 pm 07:06 PM

Digital currency contract trading: Investment strategies that coexist with high returns and potential risks. Digital currency contract trading. Unlike spot trading, investors need to predict the ups and downs of the price of digital currency and choose to go long or short contracts to make a profit. Contract trading usually uses leverage, with potential returns higher than spot trading, but also accompanied by higher risks. This article will reveal common pitfalls in digital currency contract trading and provide detailed steps for contract trading on Ouyi OKX Exchange. Risks and Traps of Digital Currency Contract Trading There are many risks hidden in the market for digital currency contracts, and criminals or platforms may use rule loopholes to make profits. Common pitfalls include: Price manipulation: manipulate market prices through centralized trading, artificially raising or lowering prices to make profits. Information asymmetry: platform or transaction

Ouyi okx trading platform app official website registration portal Ouyi okx trading platform app official website registration portal Mar 04, 2025 pm 11:27 PM

OKX trading platform, a digital asset trading platform trusted by global users. The platform provides a variety of digital asset trading services, including spot trading, futures trading, option trading, etc.

See all articles