Django 创建自定义 UserCreationForm
我在 Django 中启用了用户身份验证模块,但是当我使用 UserCreationForm 时,它只要求用户名和两个密码/密码确认字段。我还想要电子邮件和全名字段,全部设置为必填字段。
我已经这样做了:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email")
fullname = forms.CharField(label = "Full name")
class Meta:
model = User
fields = ("username", "fullname", "email", )
现在表单显示新字段,但不会将它们保存到数据库中。
我该如何解决这个问题?
I enabled the user auth module in Django, however when I use UserCreationForm
it only asks for username and the two password/password confirmation fields. I also want email and fullname fields, all set as required fields.
I've done this:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email")
fullname = forms.CharField(label = "Full name")
class Meta:
model = User
fields = ("username", "fullname", "email", )
Now the form shows the new fields but it doesn't save them to the database.
How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
User 模型中没有名为
fullname
的字段。如果您希望使用原始模型存储名称,则必须将其单独存储为名字和姓氏。
编辑:如果您只想表单中的一个字段并且仍然使用原始的 User 模型,请使用以下内容:
您可以执行以下操作:
现在您必须执行 manji 所说的操作并覆盖 save 方法,但是由于用户模型没有全名字段,它应该如下所示:
注意:您应该为全名字段添加一个干净的方法,以确保输入的全名仅包含两部分:名字和姓氏,并且包含其他有效字符。
用户模型参考源代码:
There is no such field called
fullname
in the User model.If you wish to store the name using the original model then you have to store it separately as a first name and last name.
Edit: If you want just one field in the form and still use the original User model use the following:
You can do something like this:
Now you have to do what manji has said and override the save method, however since the User model does not have a fullname field it should look like this:
Note: You should add a clean method for the fullname field that will ensure that the fullname entered contains only two parts, the first name and last name, and that it has otherwise valid characters.
Reference Source Code for the User Model:
您必须重写 UserCreationForm.save() 方法:
You have to override
UserCreationForm.save()
method:在 django 1.10 中,这是我在 admin.py 中编写的内容,将 first_name、email 和 last_name 添加到 < strong>默认 django 用户创建表单
In django 1.10 this is what I wrote in admin.py to add first_name, email and last_name to the default django user creation form