此问题专门针对 Django 2.0 答案,因为注册
模块尚不可用。
更多,这可能看起来很广泛,但我经常发现自己处于无法使用任何第三方模块的情况,因为......哦好吧......政策。我相信很多人都这么做过。我知道,查找并整理从此处或 django 文档获取的信息是一件令人头痛的事情。
<小时/>工作流程:
假设我们需要以下流程:
- 用户转到注册页面并填写以下字段:
名字
、姓氏
和电子邮件
(电子邮件将是用作用户名)。 - 用户提交表单并收到一封确认电子邮件,其中的 URL 包含唯一 token 。
- 当用户点击收到的链接时,他会被重定向到一个可以设置密码的页面。完成后,他已登录仪表板页面。
额外信息:用户稍后将使用他的电子邮件(实际上是他的用户名)和密码登录。
<小时/>具体问题:
- 模型/ View (使用 CBV)/表单/URL 会是什么样子?
最佳答案
用户模型
首先,您需要创建一个自定义 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'
<小时/>
token 生成器
第二部分是为电子邮件确认 URL 创建 token 生成器。我们可以继承内置的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()
<小时/>
注册表单
然后您应该创建一个注册表单以在我们的 View 中使用。最好的办法就是继承Django内置的UserCreationForm
并删除 username
和password
其中的字段,然后添加 email
field 。
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')
<小时/>
注册 View
在注册时,您应该使用户处于非事件状态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')
当然,不要忘记为您的注册 View 创建一个模板。
<小时/>激活 View
然后您应该为用户创建一个 View ,以使用我们在注册 View 中创建的 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')
再次强调,不要忘记为您的激活 View 创建一个模板。
<小时/>网址
最后,在 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'),
]
<小时/>
附注老实说,我还没有机会一起测试所有这些部分,但请毫不犹豫地询问是否发生了任何问题。
关于python - Django 2 - 如何使用电子邮件确认和 CBV 注册用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298114/