
Django
使用电子邮件确认和 CBV 注册用户
在 Django 2 中,用户注册是一个常见的功能。为了提高用户注册的安全性,在用户注册完成后,通常需要通过电子邮件确认用户的身份。本文将介绍如何使用 Django 的类基视图(CBV)和电子邮件确认功能来注册用户。步骤1:设置首先,我们需要在 Django 项目的设置文件中进行一些配置。我们需要配置电子邮件发送的相关信息,如邮件服务器、端口、用户名和密码等。在设置文件中找到以下部分,并进行相应的修改:PythonEMAIL_BACKEND = 'Django.core.mAIl.backends.smtp.EmAIlBackend'EMAIL_HOST = 'your_emAIl_host'EMAIL_PORT = your_emAIl_portEMAIL_HOST_USER = 'your_emAIl_username'EMAIL_HOST_PASSword = 'your_emAIl_password'EMAIL_USE_TLS = TrueDEFAULT_FROM_EMAIL = 'your_emAIl_address'替换上述代码中的 "your_emAIl_host"、"your_emAIl_port"、"your_emAIl_username"、"your_emAIl_password" 和 "your_emAIl_address" 为你自己的电子邮件服务器相关信息。步骤2:创建注册表单接下来,我们需要创建一个注册表单,用于用户输入注册信息。在 Django 项目的某个应用中创建一个 forms.py 文件,并添加以下代码:
Pythonfrom Django import formsfrom Django.contrib.auth.forms import UserCreationFormfrom Django.contrib.auth.models import Userclass RegistrationForm(UserCreationForm): emAIl = forms.EmAIlField() class Meta: model = User fields = ('username', 'emAIl', 'password1', 'password2')上述代码中,我们使用 Django 的内置 UserCreationForm 表单作为基类,并添加了一个额外的 emAIl 字段。这样用户在注册时就需要输入邮箱。步骤3:创建注册视图接下来,我们需要创建一个注册视图,用于处理用户注册的逻辑。在 Django 项目的某个应用中创建一个 views.py 文件,并添加以下代码:Pythonfrom Django.contrib.auth import get_user_modelfrom Django.contrib.sites.shortcuts import get_current_sitefrom Django.core.mAIl import EmAIlMessagefrom Django.shortcuts import render, redirectfrom Django.template.loader import render_to_stringfrom Django.urls import reverse_lazyfrom Django.utils.http import urlsafe_base64_encode, urlsafe_base64_decodefrom Django.utils.encoding import force_bytes, force_textfrom Django.views.generic import CreateViewfrom .forms import RegistrationFormfrom .tokens import account_activation_tokenUser = get_user_model()class SignUpView(CreateView): form_class = RegistrationForm template_name = 'registration/signup.html' success_url = reverse_lazy('signup_success') def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mAIl_subject = 'Activate your account' message = render_to_string('registration/activation_emAIl.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') emAIl = EmAIlMessage(mAIl_subject, message, to=[to_emAIl]) emAIl.send() return redirect(self.success_url)上述代码中,我们使用了 Django 的 CreateView 类作为基类,继承了注册表单和相关逻辑。在 form_valid 方法中,我们首先保存用户信息,但将 is_active 属性设为 False,表示用户账户未激活。然后,我们生成一个包含激活链接的电子邮件,并发送给用户。最后,将用户重定向到注册成功页面。步骤4:创建激活视图现在,我们需要创建一个激活视图,用于处理用户点击激活链接后的逻辑。在 Django 项目的某个应用中创建一个 views.py 文件,并添加以下代码:Pythonfrom Django.contrib.auth import get_user_modelfrom Django.http import HttpResponsefrom Django.shortcuts import redirectfrom Django.utils.encoding import force_textfrom Django.utils.http import urlsafe_base64_decodefrom Django.views import Viewfrom .tokens import account_activation_tokenUser = get_user_model()class ActivateAccountView(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): user.is_active = True user.save() return HttpResponse('Thank you for activating your account. You can now login.') else: return HttpResponse('Activation link is invalid or has expired.')上述代码中,我们使用了 Django 的 View 类作为基类。在 get 方法中,我们首先解码 uidb64,然后通过解码后的 uid 获取用户对象。如果用户存在,并且激活令牌有效,我们将激活用户账户。最后,返回相应的提示信息。步骤5:创建 URL 配置最后,我们需要在 Django 项目的 URL 配置文件中添加相应的 URL 配置。在 Django 项目的主 URL 配置文件中,添加以下代码:Pythonfrom Django.urls import pathfrom .views import SignUpView, ActivateAccountViewurlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('activate/<str:uidb64>/<str:token>/', ActivateAccountView.as_view(), name='activate'),]上述代码中,我们将注册视图和激活视图分别映射到了 '/signup/' 和 '/activate/Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号