在 Django 中创建电子邮件验证的最佳方法是什么?

问题描述 投票:0回答:2

所以,我的想法是:

  • 创建用户
  • 验证码已通过电子邮件发送
  • 确认电子邮件和活跃用户

我尝试了这个视图,创建了用户但没有激活它。然后将用户代码与生成的代码进行比较。

但它不起作用

def createuser(request):
    form = MyUserCreationForm()
    # confirmed = User.is_email_confirmed
    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():     

            code = User.objects.make_random_password(length=6,allowed_chars='1234567890')

            user = form.save(commit=False)
            user.username = user.username.lower()
            user.email = user.email.lower()
            user.is_active = False
            
            user.profile.code = code
            user.save()
            login(request,user)
            

        
    
            subject = 'Confirm your email' 
            confirmation_code = code
            message = f'Confirm your email with this code: {confirmation_code}'
            from_email = '[email protected]'
            to_email = request.POST['email']
            send_mail(subject,message,from_email,[to_email]).save()
            user.save()
            return redirect('verification')
        
        else:
            messages.error(request,'An error occured during your registration')
    context = {'form':form}
    return render(request, 'signup.html', context)

def verifycode(request):
    if request.method == 'POST':
        code = request.POST['code']
        
        # Check if the verification code matches
        if request.user.profile.code == code:
            # Mark the user as active
            request.user.is_active = True
            request.user.save()
            # Log in the user
            login(request, request.user)
            return redirect('home')
        else:
            # Handle incorrect verification code
            return render(request, 'verify.html', {'error': 'Incorrect verification code'})
    else:
        return render(request, 'verify.html')

还有其他(和功能性的)方法吗?

django-views email-validation
2个回答
1
投票

首先,从您提供的代码中,保存用户的个人资料。添加保存到

user.profile.save() after user.profile.code = code

邮件发送,不需要保存,可以去掉 .save()

    send_mail(subject,message,from_email,[to_email]).save()

喜欢

    send_mail(subject,message,from_email,[to_email])  # Removed .save()

最好是验证后登录,这样你就可以在def createuser中注册后删除登录。

还有其他方法,你可以看这个 https://pypi.org/project/Django-Verify-Email/ 还有例子。

我希望这有帮助!


0
投票

当您寻求替代方案时,我对 https://pypi.org/project/django-invitations/ 有一些积极的经验,您也可以在工作流程中使用它。 Jazzband 维护人员很棒,但在这个模块上速度相当慢,但大多数东西都可以正常工作..:)

© www.soinside.com 2019 - 2024. All rights reserved.