我是否可以通过 CBV 创建用户实例而不是先创建表单?(姜戈)



现在我使用 forms.py、models.py 、views.py 创建了一个如下所示的用户实例,它可以工作:

models.py:

from django.db import models
from django.contrib import auth
from django.utils import timezone
# Create your models here.
class User(auth.models.User, auth.models.PermissionsMixin):
def __str__(self):
return "@{}".format(self.username)

views.py:

from django.shortcuts import render
from django.views import generic
from django.urls import reverse,reverse_lazy
from . import forms, models
from django.contrib.auth import get_user_model
# Create your views here.

class SignUp(generic.CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"

forms.py

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class UserCreateForm(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
# below code is not necessary, just want to customize the builtin attribtue of
# the User class
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].label = "Display name"
self.fields["email"].label = "Email address"

但是,我想知道我是否可以通过编辑如下所示的 views.py 来创建用户。 views.py:

from django.shortcuts import render
from django.views import generic
from django.urls import reverse,reverse_lazy
from . import forms, models
from django.contrib.auth import get_user_model
# Create your views here.

class SignUp(generic.CreateView):
model = get_user_model()
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"
fields = ("username", "email","password1","password2")

# below is original version
# class SignUp(generic.CreateView):
#     form_class = forms.UserCreateForm
#     success_url = reverse_lazy("login")
#     template_name = "accounts/signup.html"

当我在"accounts/signup.html"中时出现错误 为用户指定的未知字段(密码 1((密码 2(。

如果我删除这两个字段,"password1","password2",我将能够到达"accounts/signup.html"并创建一个没有密码的用户实例,我可以在管理页面中看到它,尽管它没有用。

所以我想是否有任何好方法可以只使用泛型创建用户。创建视图和用户模型?

为什么我收到为用户指定的错误未知字段(密码 1((密码 2(?

期待很快得到任何建议!

UserCreationForm

负责检查该password1 == password2,然后对密码进行哈希处理并设置user.password

如果您没有自定义表单,则不能使用password1password2,因为这些不是模型字段。

可以将password添加到视图中的fields,但它不会显示为密码输入。您还需要向视图添加代码,以便在保存用户时对密码进行哈希处理。

因此,可以从SignUp中删除表单,但我不建议这样做,因为它会使视图更加复杂,并且可能会失去功能。

最新更新