django实现用户注册以及邮箱验证功能

用户注册:

类似于用户登陆,同样在users.views.py中添加RegisterView(View)类,其中对表单的get和post作出处理。
如果是get方法,重新返回register页面让用户进行填写。

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

method = POST时,用户注册逻辑:

    def post(self, request):
        # 实例化form,验证每个字段是否合法
        register_form = RegisterForm(request.POST)
        pre_check = register_form.is_valid()
        if pre_check:
            # 取出email和password
            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.is_active = False
            # 将明文转换为密文赋给password
            user_profile.password = make_password(pass_word)
            user_profile.save()  # 保存到数据库
            # 此处加入了邮箱验证的手段
            send_register_email(user_name, "register")
            return render(request, "login.html")
        else:
            # form表单验证失败,将错误信息传给前端
            return render(request, "register.html", {"register_form": register_form})

在form.py中添加RegisterForm类对给出表单处理类:

class RegisterForm(forms.Form):
    # 不能为空
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, min_length=6, max_length=20)
    # 出错信息
    captcha = CaptchaField(error_messages={"invalid":u"验证码错误"})

以下为对应的前端代码,其中添加了了django的模版用法,均以{% %}的形式在html中加入逻辑, 避免了python代码的直接插入,方便维护和修改。

<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
                        <div class="form-group marb20 {% if register_form.errors.email %}errorput{% endif %}">
                            <label>邮     箱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>密     码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>验 证 码label>
                            {{ register_form.captcha }}
                        div>
                        <div class="error btns" id="jsEmailTips">{% for key,error in register_form.errors.items %}{{ error }}{% endfor %} {{ msg }}div>
                        <div class="auto-box marb8">
                        div>
                        <input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="注册并登录" />
                        {% csrf_token %}
                    form>

{% csrf_token %}是django为了在用户提交表单时防止跨站攻击所做的保护,在表单最后没有加入的话,不能正常提交
表单中有一项为验证码,在django中可以使用django-simple-captcha模块实现:

  • url(r’^captcha/’, include(‘captcha.urls’)) 配置url
  • {{ register_form.captcha }} 配置前端

邮箱验证:

在users.py中添加了邮箱验证的model:

class EmailVerifyRecord(models.Model):
    # 验证码
    code = models.CharField(max_length=20, verbose_name=u"验证码")
    email = models.EmailField(max_length=50, verbose_name=u"邮箱")
    # 包含注册验证和找回验证
    send_type = models.CharField(verbose_name=u"验证码类型", max_length=10, choices=(("register",u"注册"), ("forget",u"找回密码")))
    send_time = models.DateTimeField(verbose_name=u"发送时间", default=datetime.now)
    class Meta:
        verbose_name = u"邮箱验证码"
        verbose_name_plural = verbose_name
    def __unicode__(self):
        return '{0}({1})'.format(self.code, self.email)

在setting.py中添加配置邮箱信息:

EMAIL_HOST = "smtp.163.com"   # 服务器
EMAIL_PORT = 25               # 一般情况下都为25
EMAIL_HOST_USER = "[email protected]"   # 账号
EMAIL_HOST_PASSWORD = "password"  # 密码
EMAIL_USE_TLS = False             # 一般都为False
EMAIL_FROM = "[email protected]"        # 邮箱来自

创建utils包,新建email_send .py

from random import Random # 用于生成随机码 
from django.core.mail import send_mail # 发送邮件模块
from users.models import EmailVerifyRecord # 邮箱验证model
from MxOnline.settings import EMAIL_FROM  # setting.py添加的的配置信息

# 生成随机字符串
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_register_email(email, send_type="register"):
    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 = ""
    email_body = ""
    # 如果为注册类型
    if send_type == "register":
        email_title = "注册激活链接"
        email_body = "请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}".format(code)
        # 发送邮件
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass

然后将用户变为活跃用户,加入相关的view:

class ActiveUserView(View):
    def get(self, request, active_code):
    # 用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()
                        else:
            return render(request, "active_fail.html")
        return render(request, "login.html")

配置生成页面的url:

url(r'^active/(?P.*)/$', ActiveUserView.as_view(), name="user_active"),  # 提取出active后的所有字符赋给active_code

至此,便可将is_active加入到登陆的限制当中:

                if user.is_active:
                    login(request, user)  # 调用login方法登陆账号
                    return render(request, "index.html")
                else:
                    return render(request, "login.html", {"msg": u"用户未激活"})

你可能感兴趣的:(Django,Python)