Django实现邮箱验证功能

1 注册支持smtp服务的邮箱

你需要注册一个能发送邮件的邮箱,支持smtp服务的邮箱,本文根据网易云邮箱来写,如何注册请自行Google

2 创建class

from django.db import models

   '''
   用户类
   '''
   id = models.AutoField(primary_key=True, verbose_name='用户id')
   username = models.CharField(max_length=128)
   password = models.CharField(max_length=256)
   nick_name = models.CharField(null=True, blank=True, max_length=20, verbose_name='用户昵称')
   email = models.EmailField(unique=True, verbose_name='用户邮箱')
   header_image = models.ImageField(upload_to='static/images/', default='static/images/mz1.jpg')
   age = models.IntegerField(default=0, verbose_name='用户年龄')
   gender = models.CharField(null=True, blank=True, max_length=5, verbose_name='用户性别')
   c_time = models.DateTimeField(auto_now_add=True, verbose_name='用户注册时间')
   phone = models.IntegerField(null=True, blank=True, verbose_name='用户手机号')
   hometown = models.CharField(null=True, blank=True, max_length=30, verbose_name='用户家乡')
   intro = models.TextField(null=True, blank=True, verbose_name='用户简介')
   has_confirmed = models.BooleanField(default=False)
   def __str__(self): 
       return self.nick_name

   class Meta:
       '''
       元类
       '''
       ordering = ['-c_time']
       verbose_name = '用户'
       verbose_name_plural = '用户'
class ConfirmString(models.Model):
   '''
   确认code类
   '''
   code = models.CharField(max_length=256)
   user = models.OneToOneField(User)
   c_time = models.DateTimeField(auto_now_add=True)

   def __str__(self):
       return self.user.name + ': ' + self.code

   class Meta:
       ordering = ['-c_time']
       verbose_name = '确认码'
       verbose_name_plural = '确认码'

3 修改视图

import datetime
import pytz

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.hashers import make_password, check_password


from . import models
from django.conf import settings

def make_confirm_string(user):
    from uuid import uuid4
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    code = str(uuid4())
    models.ConfirmString.objects.create(code=code, user=user)
    return code

def user_register(request):
    '''
    用户注册视图函数
    :param request:
    :return:
    '''
    if request.session.get('is_login', None):
        return redirect('/')
    if request.method == 'GET':
        return render(request, 'user/user_register.html', {})
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        re_password = request.POST.get('re_password')
        email = request.POST.get('email')
        try:
            user = models.User.objects.get(username=username)
            return render(request, 'user/user_register.html', {'error_code': -1, 'error_msg': '账号已经存在,换个账号试试吧!'})
        except:
            try:
                user = models.User.objects.get(email=email)
                return render(request, 'user/user_register.html',
                              {'error_code': -2, 'error_msg': '邮箱已经存在,换个昵称试试吧!'})
            except:
                if password != re_password:
                    return render(request, 'user/user_register.html',
                                  {'error_code': -3, 'error_msg': '两次密码输入不一致,请重新注册'})
                else:
                    password = make_password(password, None, 'pbkdf2_sha256')
                    user = models.User(username=username, password=password, email=email)
                    user.save()
                    code = make_confirm_string(user)
                    send_email(email, code)

                    message = '请前往注册邮箱,进行邮件确认!'
                    return render(request, 'user/confirm.html', locals())


def send_email(email, code):
    from django.core.mail import EmailMultiAlternatives

    subject = '来自www.1117.link的注册确认邮件'

    text_content = '''欢迎注册www.1117.link,这里是大鱼的论坛站点,专注于Python和Django技术的分享!\
                        如果你看到这条消息,说明你的邮箱服务器不提供HTML链接功能,请联系管理员!'''

    html_content = '''
                        

感谢注册www.1117.link,\ 这里是大鱼的博客和教程站点,专注于Python和Django技术的分享!

请点击站点链接完成注册确认!

此链接有效期为{}天!

'''.format('127.0.0.1:80', code, settings.CONFIRM_DAYS) msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email]) msg.attach_alternative(html_content, "text/html") msg.send() def user_confirm(request): code = request.GET.get('code', None) message = '' try: confirm = models.ConfirmString.objects.get(code=code) except: message = '无效的确认请求!' return render(request, 'user/confirm.html', locals()) c_time = confirm.c_time now = datetime.datetime.now() now = now.replace(tzinfo=pytz.timezone('UTC')) if now > c_time + datetime.timedelta(settings.CONFIRM_DAYS): confirm.user.delete() message = '您的邮件已经过期!请重新注册!' return render(request, 'user/confirm.html', locals()) else: confirm.user.has_confirmed = True confirm.user.save() confirm.delete() message = '恭喜您注册成功,赶快尝试登录吧!' return render(request, 'user/confirm.html', locals())

4 user/confirm.html页面

{% block title %}注册确认{% endblock %}
{% block content %}
    

{{ message }}

{% endblock %}

5 settings文件的配置

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'  # 邮箱服务地址 这里是163邮箱的
EMAIL_PORT = 25  # 端口号
EMAIL_HOST_USER = '[email protected]'  # 邮箱帐号
EMAIL_HOST_PASSWORD = 'nan521'  # 邮箱密码

CONFIRM_DAYS = 7
  1. urls配置
    url(r'^confirm/$', views.user_confirm, name='user_confirm'),

你可能感兴趣的:(Django实现邮箱验证功能)