码迷,mamicode.com
首页 > 其他好文 > 详细

django 增加验证邮箱功能

时间:2019-01-02 01:18:57      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:efi   utils   random   存储   rom   默认   int   ==   Fix   

在user文件夹下新建python包,utils

在包内新建文件email_send.py,其中包括验证字符串随机码的产生,数据库的存储和email的发送

# -*- coding: utf-8 -*-
# 作者:神秘藏宝室
# 日期:2019/1/1 22:21
from random import Random
from django.core.mail import send_mail

from users.models import EmailVerifyRecord
from waaaxWeb.settings import EMAIL_FROM


def 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 str


def send_registr_email(email, sendtpye='register'):
    email_record = EmailVerifyRecord()
    code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = sendtpye
    email_record.save()

    email_title = ''
    email_body = ''
    if sendtpye == 'register':
        email_title = u'维可思电子网注册激活链接'
        email_body = u'请点击下面的链接激活您的账号:http://127.0.0.1:8000/active/{0}'.format(code)

        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        return send_status

因为用到发送email需要在settings下设置EMAIL的属性

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp-mail.outlook.com'                       #SMTP地址 例如: smtp.163.com
EMAIL_PORT = 25                       #SMTP端口 例如: 25
EMAIL_HOST_USER = 'waaax@outlook.com'                  #qq的邮箱 例如: xxxxxx@163.com
EMAIL_HOST_PASSWORD = ''              #我的邮箱密码 例如  xxxxxxxxx
EMAIL_SUBJECT_PREFIX = u'django'       #为邮件Subject-line前缀,默认是'[django]'
EMAIL_USE_TLS = True                  #与SMTP服务器通信时,是否启动TLS链接(安全链接)。默认是false
EMAIL_FROM = 'waaax@outlook.com'

调试下正常注册可以收到email验证了

修改views下的跳转逻辑

class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form':register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get("email", "")
            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.password = make_password(pass_word)
            user_profile.save()

            status = send_registr_email(user_name, 'register')
            if status:
                return render(request, "login.html")
            else:
                return render(request, "register.html", {"msg": u"发送邮件失败!"})
        else:
            return render(request, "register.html", {"register_form": register_form})

修改register.html内的错误提示

<div class="error btns" id="jsEmailTips">{% for key,error in register_form.errors.items %} {{ error }} {% endfor %}{{ msg }}</div>

修改输入框的错误提示

<div class="form-group marb20 {% if register_form.errors.email %}errorput{% endif %}">
                            <label>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</label>
                            <input  type="text" id="id_email" name="email" value="{{ register_form.email.value }}" placeholder="请输入您的邮箱地址" />
                        </div>
                        <div class="form-group marb8 {% if register_form.errors.password %}errorput{% endif %}">
                            <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label>
                            <input type="password" id="id_password" name="password"  value="{{ register_form.password.value }}" placeholder="请输入6-20位非中文字符密码" />
                        </div>
                        <div class="form-group marb8 captcha1 {% if register_form.errors.captcha %}errorput{% endif %}">
                            <label>验&nbsp;证&nbsp;码</label>
                            {{ register_form.captcha }}
                        </div>

增加邮箱激活功能,首先要修改注册时候is_active的初始值为未激活

class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form':register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get("email", "")
            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.password = make_password(pass_word)
            user_profile.is_active = False
            user_profile.save()

            status = send_registr_email(user_name, 'register')
            if status == 1:
                return render(request, "login.html")
            else:
                return render(request, "register.html", {"msg": u"发送邮件失败!"})
        else:
            return render(request, "register.html", {"register_form": register_form})

新建一个激活用的view类AciveUserView

class AciveUserView(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, 'login.html')

增加urls

url(r'^active/(?P<active_code>.*)/$', AciveUserView.as_view(), name="user_acive"),

这样当访问邮箱收到的激活链接时候就会改变激活状态,然后跳转到登陆界面

重新修正登陆要求,必须激活

class LoginView(View):
    def get(self, request):
        return render(request, 'login.html', {})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, "index.html")
                else:
                    return render(request, "login.html", {"msg": u"用户未激活"})
            else:
                return render(request, "login.html", {"msg": u"用户名或者密码错误!"})
        else:
            return render(request, "login.html", {"login_form": login_form})

OK!已经可以正确显示未激活状态 ,对激活链接进行激活 和 激活直接登陆

django 增加验证邮箱功能

标签:efi   utils   random   存储   rom   默认   int   ==   Fix   

原文地址:https://www.cnblogs.com/Mysterious/p/10206575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!