【发布时间】:2020-06-23 09:46:37
【问题描述】:
现在我使用 forms.py、models.py、views.py 创建了一个像下面这样的 User 实例,它可以工作了:
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 来创建用户,如下所示。 视图.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”中时出现错误 为用户指定的未知字段 (password1) (password2)。
如果我删除这两个字段“password1”、“password2”,我将能够访问“accounts/signup.html”并创建一个没有密码的用户实例,尽管它没有用,但我可以在管理页面中看到它.
所以我想知道是否有任何好方法可以仅使用 generic.Createview 和 User 模型来创建用户?
为什么我会收到错误 Unknown field(s) (password1) (password2 )specified for User?
期待尽快得到任何建议!
【问题讨论】: