Django 中的电子邮件验证

Email verification in Django

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

问题来了:

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

有什么解决办法吗?我尝试并关注:

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

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

有没有Django的第三方模块或者我提到的需求的解决方案?

你的第一个问题我有答案了:

如果您根据 PasswordResetView + PasswordResetConfirmView 重置用户密码,您可以执行以下操作:

PasswordResetView 负责向用户发送电子邮件。它使用自己的表单来输入用户电子邮件 -PasswordResetForm。您可以创建自己的表单并从 PasswordResetForm 继承它。 例如:


class PRForm(PasswordResetForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email__iexact=email, is_active=True).exists():
            msg = "There is no user with this email."
            self.add_error('email', msg)
        return email

# User – your user model or any custom model if you have one instead of the default one

此代码不允许控制器向您的数据库中没有的电子邮件地址发送电子邮件。

然后在您的 VIEW 中指定此表单:


class PassResView(RatelimitMixin,  PasswordResetView):
    success_url = 
    from_email = 
    subject_template_name =
    email_template_name =
    success_message = 
    template_name = 
    form_class = PRForm  # here is a custom form
    ratelimit_key = 'ip'
    ratelimit_rate = '10/5m'
    ratelimit_block = True
    ratelimit_method = ('GET', 'POST')

RatelimitMixin 将不允许有人通过 运行 你的 BD 来暴力破解你的数据库。您可以使用或不使用它-由您决定。

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

型号

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
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()

观看次数

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!')

表格

from django.contrib.auth.forms import UserCreationForm


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

电子邮件模板

{% 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:

第一个答案需要加上urls.py

path('emailVerification/<uidb64>/<token>', views.activate, name='emailActivate')

emailVerification.html一定是这样的:

    Hi ,
Please click on the link to confirm your registration,
http://{{ domain }}/emailVerification/{{ uid }}/{{ token }}