[英]How to specify a custom 404 view for Django using Class Based Views?
[英]How to make a signup view using Class based views in Django?
當我開始使用 Django 時,我使用 FBV(基於 Function 的視圖)來處理幾乎所有事情,包括注冊新用戶。
但是隨着我對項目的深入研究,我意識到基於類的視圖通常更適合大型項目,因為它們更干凈且可維護,但這並不是說 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"
以及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']
您可以使用 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'
有關更多信息,請查看https://learndjango.com/tutorials/django-signup-tutorial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.