Django 2 -如何使用电子邮件确认和CBV注册用户?

mfuanj7w  于 2022-11-18  发布在  Go
关注(0)|答案(4)|浏览(131)

这个问题专门针对Django 2.0的答案,因为registration模块还没有提供。

  • 更多,这可能看起来很宽泛,但我经常发现自己在我不能使用任何第三方模块的情况下,因为...哦,好吧..政策。我相信很多人这样做。我知道,寻找和整理从这里或django文档的信息是一个头痛。*

工作流程:

假设我们需要以下流程:
1.用户转到注册页面并填写以下字段:first_namelast_nameemail(电子邮件将用作用户名)。
1.用户提交表单并收到一封确认电子邮件,其中包含一个包含唯一令牌的URL。
1.当用户点击接收到的链接时,他将被重定向到一个页面,在那里他将设置他的密码。完成后,他将登录到 Jmeter 板页面。

  • 额外信息:用户稍后将使用其电子邮件(实际上是其用户名)和密码登录。*

具体问题:

  • 模型/视图(使用CBV)/表单/URL看起来如何?
cbwuti44

cbwuti441#

用户模型

首先,您需要创建一个自定义的User模型和一个自定义的UserManager,以删除username字段并使用email
models.py中,UserManager应如下所示:

from django.contrib.auth.models import BaseUserManager

class MyUserManager(BaseUserManager):
    """
    A custom user manager to deal with emails as unique identifiers for auth
    instead of usernames. The default that's used is "UserManager"
    """
    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The Email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')
        return self._create_user(email, password, **extra_fields)

User型号:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, null=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    USERNAME_FIELD = 'email'
    objects = MyUserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

最后在settings.py中:

AUTH_USER_MODEL = 'your_app_name.User'

令牌生成器

第二部分是为电子邮件确认网址创建一个令牌生成器。我们可以继承内置的PasswordResetTokenGenerator,使之更容易。
创建tokens.py

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

注册表单

最好的方法是继承Django内置的UserCreationForm,删除其中的usernamepassword字段,然后添加一个email字段。forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name')

注册视图

在注册过程中,您应该将用户设置为非活动状态user.is_active = False,没有密码set_unusable_password(),直到用户完成激活。另外,我们将创建一个激活URL,并在完成注册后通过电子邮件发送给用户。
views.py中:

from django.views import View
from django.http import HttpResponse
from django.shortcuts import render
from .forms import SignupForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from .tokens import account_activation_token
from django.core.mail import EmailMessage

class Signup(View):
    def get(self, request):
        form = SignupForm()
        return render(request, 'signup.html', {'form': form})

    def post(self, request):
        form = SignupForm(request.POST)
        if form.is_valid():
            # Create an inactive user with no password:
            user = form.save(commit=False)
            user.is_active = False
            user.set_unusable_password()
            user.save()

            # Send an email to the user with the token:
            mail_subject = 'Activate your account.'
            current_site = get_current_site(request)
            uid = urlsafe_base64_encode(force_bytes(user.pk))
            token = account_activation_token.make_token(user)
            activation_link = "{0}/?uid={1}&token{2}".format(current_site, uid, token)
            message = "Hello {0},\n {1}".format(user.username, activation_link)
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')

当然,不要忘记为您的注册视图创建一个模板。

激活视图

然后,您应该创建一个视图,让用户使用我们在注册视图中创建的URL来激活他的帐户。我们还将使用内置的Django的SetPasswordForm来允许用户设置密码。
views.py为单位:

from django.contrib.auth import get_user_model, login, update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from .tokens import account_activation_token

User = get_user_model()

class Activate(View):
    def get(self, request, uidb64, token):
        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):
            # activate user and login:
            user.is_active = True
            user.save()
            login(request, user)
            
            form = PasswordChangeForm(request.user)
            return render(request, 'activation.html', {'form': form})
            
        else:
            return HttpResponse('Activation link is invalid!')
            
    def post(self, request):
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user) # Important, to update the session with the new password
            return HttpResponse('Password changed successfully')

同样,不要忘记为激活视图创建一个模板。

URL

最后,在urls.py中:

from . import views
from django.urls import path

urlpatterns = [
    ...
    path('signup/', views.signup.as_view(), name='signup'),
    path('activate/<str:uid>/<str:token>', views.activate.as_view(), name='activate'),
]

P.S.老实说,我还没有机会一起测试所有这些部件,但如果有任何问题发生,请不要犹豫。

o3imoua4

o3imoua42#

除了Peter的回答,如果你使用Django 2,那么编码和解码部分会有一些不同。

  • 正在编码:*

更改'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),

  • 正在解码 *

更改uid = force_text(urlsafe_base64_decode(uidb64))
uid = urlsafe_base64_decode(uidb64).decode()

Django 3编辑:

  • 编码:* uid = urlsafe_base64_encode(force_bytes(user.pk))
  • 解码:* uid = urlsafe_base64_decode(uidb64).decode()
xv8emn3q

xv8emn3q3#

您可以呼叫密码重设表单,从要求传递使用者的电子邮件。这会使用内建验证传送链接。您可能想要取代电子邮件和密码表单的预设模板。

from django.contrib.auth.forms import PasswordResetForm

# either the request or domain_override kwarg is needed
form = PasswordResetForm({'email': user.email})
        if form.is_valid():
            return form.save(
                from_email='email@email.com',
                # domain_override='your_domain',
                request=request, 
                email_template_name='registration/password_reset_email.html'
            )

非常肯定你需要一个现有的密码,这样你就可以创建一个临时的虚拟密码

password = User.objects.make_random_password()
user.set_password(password)
l7wslrjt

l7wslrjt4#

感谢分享,我使用上述方法生成**“Djoser”**激活电子邮件,以及工作。
我修改了以下内容:
我没有创建新的令牌生成器,而是使用了Django内置的令牌生成器,Djoser也使用了它:

from django.contrib.auth.tokens import default_token_generator

你还需要djoser utils:

from djoser import utils

uid = utils.encode_uid(user.pk)

激活链接根据Django设置中的Djoser激活链接修改:

activation_link = "http://{0}/api/user/activate/{1}/{2}".format(current_site, uid, token)

相关问题