Django注册-邮件激活

Posted learn643794461

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django注册-邮件激活相关的知识,希望对你有一定的参考价值。

注册views

class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()  # 实例化register表单
        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()
            # 发激活邮件
            send_register_email(user_name, "register")
            return render(request, 'login.html')
        else:
            return render(request, 'register.html', {'register_form': register_form})

发邮件配置

settings.py

MAIL_HOST = "smtp.sina.com"
EMAIL_PORT = 25
EMAIL_HOST_USER = 'learning@163.com'
EMAIL_HOST_PASSWORD = "123456''
EMAIL_USE_TLS = False
EMAIL_FROM = "learning@163.com"

创建utils文件夹,存放常用功能- 发邮件

技术图片

email_send.py


#!/usr/bin/env python
# coding=utf-8
import string
from random import Random

from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from mxonline.settings import EMAIL_FROM


def random_str(randomlength=8):#生成随机字符串用于激活链接后缀
    str = ''
    chars = string.ascii_letters
    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="register"):#根据注册类型: 注册or找回密码来判断发哪种邮件
    email_record = EmailVerifyRecord()#每次发邮件记录都记录在EmailVerifyRecord的模型中,用于激活时判断是否有
    code = random_str(16)
    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": # 根据send_type定制发送内容
        email_title = "后台在线系统激活链接"
        email_body = "后台在线系统激活链接: http://127.0.0.1:8000/active/{}".format(code)
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email,])
        if send_status:
            pass

激活: 主要是修改UserProfile里的is_active字段

from users.models import UserProfile, EmailVerifyRecord
from utils.email_send import send_register_email

class ActiveView(View):#主要功能是修改user_profile里的is_active字段为1
    def get(self, request,active_code):
        all_reocrds = EmailVerifyRecord.objects.filter(code=active_code)
        if all_reocrds:
            for record in all_reocrds:
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
        return render(request, 'login.html')

urls配置

urlpatterns = [
    path('active/<str:active_code>/', views.ActiveView.as_view(), name="active"),
    path('xadmin/', xadmin.site.urls),
    path('captcha/', include('captcha.urls')),
]
from django.conf.urls import url
def year_archive(request, year):
    year = int(year) # convert str to int
    # Get articles from database
def detail_view(request, article_id):
    pass
def edit_view(request, article_id):
    pass
def delete_view(request, article_id):
    pass
urlpatterns = [
    url('articles/(?P<year>[0-9]{4})/', year_archive),
    url('article/(?P<article_id>[a-zA-Z0-9]+)/detail/', detail_view),
    url('articles/(?P<article_id>[a-zA-Z0-9]+)/edit/', edit_view),
    url('articles/(?P<article_id>[a-zA-Z0-9]+)/delete/', delete_view),
]
from django.urls import path
from . import views
urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug>/', views.article_detail),
]
Django默认支持以下5个转化器: 还可以自定义, 这里就不讨论了

str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
int,匹配正整数,包含0。
slug,匹配字母、数字以及横杠、下划线组成的字符串。
uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
path,匹配任何非空字符串,包含了路径分隔符

以上是关于Django注册-邮件激活的主要内容,如果未能解决你的问题,请参考以下文章

Django 实现网站注册用户邮箱验证功能

Django+xadmin打造在线教育平台

Django 发送邮件

Djoser 用户激活电子邮件 POST 示例

javaWeb实例之邮件注册激活

python-django电商项目_20191114