Roa*_*ter 1 python django django-views django-class-based-views
当我开始使用 Django 时,我使用 FBV(基于函数的视图)来处理几乎所有事情,包括注册新用户。
但是当我深入研究项目时,我意识到基于类的视图通常更适合大型项目,因为它们更干净和可维护,但这并不是说 FBV 不是。
无论如何,我将整个项目的大部分视图迁移到基于类的视图,除了一个有点令人困惑的 SignUpView。
为了在 Django 中创建 SignUpView,您需要利用CreateView和SuccessMessageMixin创建新用户以及显示确认帐户已成功创建的成功消息。
这是代码:
views.py:
from .forms import UserRegisterForm
from django.views.generic.edit import CreateView
class SignUpView(SuccessMessageMixin, CreateView):
template_name = 'users/register.html'
success_url = reverse_lazy('login')
form_class = UserRegisterForm
success_message = "Your profile was created successfully"
Run Code Online (Sandbox Code Playgroud)
并且forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'first_name']
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用 Django 的 CreateView 创建新的用户对象。
# accounts/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看https://learndjango.com/tutorials/django-signup-tutorial