[英]Am I able to create a form that is able to add a new django.contrib.auth User without logging in to the admin panel?
[英]Am I able to create a User instance by CBV rather than create a form first? (Django)
现在我使用 forms.py、models.py、views.py 来创建一个用户实例,如下所示,它可以工作:
模型.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)
视图.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 model 创建用户?
为什么我会收到错误 Unknown field(s) (password1) (password2 )specified for User?
期待尽快得到任何建议!
UserCreationForm
负责检查password1 == password2
,然后对密码进行哈希处理并设置user.password
。
如果您没有自定义表单,则不能使用password1
和password2
,因为这些不是 model 字段。
您可以将password
添加到视图中的fields
,但它不会显示为密码输入。 您还需要在视图中添加代码到 hash 保存用户时的密码。
因此,可以从SignUp
中删除表单,但我不建议这样做,因为它会使视图更加复杂,并且可能会失去功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.