Django 中的电子邮件验证 [英] Email verification in Django

查看:33
本文介绍了Django 中的电子邮件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 中有一个网络应用程序.我尝试使用令牌生成器重置密码来创建验证邮件,但它没有激活电子邮件.

遇到问题:

  1. 当用户提供电子邮件时,它应该检查电子邮件是否存在于数据库中.(DB 将使用用户电子邮件进行更新)
  2. 在验证电子邮件是否存在于数据库中后,系统会提示用户创建密码.
  3. 创建密码后,用户可以登录相应页面.

有什么解决办法吗?我尝试并遵循:

https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef

上面的帖子帮我发了邮件,但是验证邮件后用户没有激活.该帖子不符合我的要求,但我尝试检查是否可以进行电子邮件验证.

是否有针对 Django 的第三方模块或针对我提到的要求的任何解决方案?

解决方案

我想出了一个解决方案,但对于第二个要求,用户必须在创建帐户时输入密码.主要目标是验证用户提供的电子邮件.

模型

class Yourmodel(models.Model):first_name = models.CharField(max_length=200)second_name = models.CharField(max_length=200)email = models.EmailField(max_length=100)

代币

from django.contrib.auth.tokens import PasswordResetTokenGenerator从 django.utils 导入六类 TokenGenerator(PasswordResetTokenGenerator):def _make_hash_value(自我,用户,时间戳):返回 (六.text_type(user.pk) + 六.text_type(时间戳) +六.text_type(user.is_active))account_activation_token = TokenGenerator()

观看次数

from django.contrib.auth import get_user_model从 django.utils.http 导入 urlsafe_base64_encode, urlsafe_base64_decode从 django.contrib.sites.shortcuts 导入 get_current_site从 .tokens 导入 account_activation_token从 django.core.mail 导入 send_mail定义注册(请求):用户 = get_user_model()如果 request.method == 'POST':form = SignupForm(request.POST)如果 form.is_valid():email = form.cleaned_data.get('email')如果 Yourmodel.objects.filter(email__iexact=email).count() == 1:用户 = form.save(commit=False)user.is_active = False用户保存()current_site = get_current_site(请求)mail_subject = '激活您的帐户.'message = render_to_string('email_template.html', {'用户':用户,域":current_site.domain,'uid': urlsafe_base64_encode(force_bytes(user.pk)),'token': account_activation_token.make_token(user),})to_email = form.cleaned_data.get('email')send_mail(mail_subject, message, 'youremail', [to_email])return HttpResponse('请确认您的电子邮件地址以完成注册')别的:表格 = 注册表格()返回渲染(请求,'regform.html',{'form':form})定义激活(请求,uidb64,令牌):用户 = get_user_model()尝试:uid = force_text(urlsafe_base64_decode(uidb64))用户 = User.objects.get(pk=uid)除了(类型错误,值错误,溢出错误,User.DoesNotExist):用户 = 无如果用户不是 None 和 account_activation_token.check_token(user, token):user.is_active = True用户保存()return HttpResponse('感谢您的电子邮件确认.现在您可以登录您的帐户.')别的:return HttpResponse('激活链接无效!')

表单

from django.contrib.auth.forms import UserCreationForm类 SignupForm(UserCreationForm):元类:模型 = 用户字段=('用户名','电子邮件','密码1','密码2')

电子邮件模板

{% autoescape off %}你好 ,请点击链接确认您的注册,http://{{ 域 }}{% url '激活' uidb64=uid token=token %}{% endautoescape %}

regform.html

{% csrf_token %}{% 用于表单 %} 中的字段<label >{{ field.label_tag }}</label>{{ 场地 }}{% 结束为 %}

<块引用>

如果您不想与模型中的电子邮件地址进行比较,您可以跳过,这会将电子邮件发送到提供的电子邮件地址注册时无需进一步验证.

email = form.cleaned_data.get('email')如果 Yourmodel.objects.filter(email__iexact=email).count() == 1:

I am having a web-app in Django. I tried using the tokengenerator for password reset to create a verification mail, it's not activating the email.

Coming to the problem:

  1. While the user provides email, it should check whether the email is present in the DB. (DB will be updated with user emails)
  2. After verifying whether the email is present in the DB, the user is prompted to create a password.
  3. After creating a password user can log in to the respective page.

Is there any solution? I tried and followed:

https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef

The above post helped me to send the email, but the user is not activated after verifying the email. The post doesn't meet my requirement, though I tried to check whether email verification is possible.

Is there any third-party module for Django or any solution for the requirements I have mentioned?

解决方案

I figured out a solution , but for the second requirement user has to input the password at the time of account creation . The main goal was to verify the user supplied email.

Models

class Yourmodel(models.Model):
    first_name = models.CharField(max_length=200)
    second_name = models.CharField(max_length=200)
    email = models.EmailField(max_length=100)

Tokens

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()

Views

from django.contrib.auth import get_user_model
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.contrib.sites.shortcuts import get_current_site
from .tokens import account_activation_token
from django.core.mail import send_mail

def signup(request):
    User = get_user_model()
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            if Yourmodel.objects.filter(email__iexact=email).count() == 1:
                user = form.save(commit=False)
                user.is_active = False
                user.save()
                current_site = get_current_site(request)
                mail_subject = 'Activate your account.'
                message = render_to_string('email_template.html', {
                            'user': user,
                            'domain': current_site.domain,
                            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                            'token': account_activation_token.make_token(user),
                        })
                to_email = form.cleaned_data.get('email')
                send_mail(mail_subject, message, 'youremail', [to_email])
                return HttpResponse('Please confirm your email address to complete the registration')
     else:
        form = SignupForm()
    return render(request, 'regform.html', {'form': form})

def activate(request, uidb64, token):
    User = get_user_model()
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')

Forms

from django.contrib.auth.forms import UserCreationForm


class SignupForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

Email Template

{% autoescape off %}
Hi ,
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

regform.html

{% csrf_token %}
{% for field in form %}
<label >{{ field.label_tag }}</label>
{{ field }}
{% endfor %}

If you don't want to compare with email address in your model you can skip, this will send the email to the email address which was supplied at the time registration without further validation.

email = form.cleaned_data.get('email')
if Yourmodel.objects.filter(email__iexact=email).count() == 1:

这篇关于Django 中的电子邮件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆