[英]How to make a signup view using Class based views in Django?
When I started to use Django, I was using FBVs ( Function Based Views ) for pretty much everything including signing up for new users.当我开始使用 Django 时,我使用 FBV(基于 Function 的视图)来处理几乎所有事情,包括注册新用户。
But as I delved deep more into projects, I realized that Class-Based Views are usually better for large projects as they are more clean and maintainable but this is not to say that FBVs aren't.但是随着我对项目的深入研究,我意识到基于类的视图通常更适合大型项目,因为它们更干净且可维护,但这并不是说 FBV 不是。
Anyway, I migrated most of my whole project's views to Class-Based Views except for one that was a little confusing, the SignUpView.无论如何,我将整个项目的大部分视图迁移到基于类的视图,除了一个有点令人困惑的 SignUpView。
In order to make SignUpView in Django, you need to utilize CreateView
and SuccessMessageMixin
for creating new users as well as displaying a success message that confirms the account was created successfully.为了在 Django 中创建 SignUpView,您需要使用
CreateView
和SuccessMessageMixin
来创建新用户并显示确认帐户已成功创建的成功消息。
Here's the code:这是代码:
views.py
: 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"
and, the forms.py
:以及
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']
You can use Django's CreateView for creating a new user object.您可以使用 Django 的 CreateView 来创建新用户 object。
# 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'
For more info, check https://learndjango.com/tutorials/django-signup-tutorial有关更多信息,请查看https://learndjango.com/tutorials/django-signup-tutorial
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.