Django 创建自定义 UserCreationForm

发布于 2024-11-02 10:23:15 字数 544 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

空城仅有旧梦在 2024-11-09 10:23:15

User 模型中没有名为 fullname 的字段。

如果您希望使用原始模型存储名称,则必须将其单独存储为名字和姓氏。

编辑:如果您只想表单中的一个字段并且仍然使用原始的 User 模型,请使用以下内容:

您可以执行以下操作:

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 = "First name")

    class Meta:
        model = User
        fields = ("username", "fullname", "email", )

现在您必须执行 manji 所说的操作并覆盖 save 方法,但是由于用户模型没有全名字段,它应该如下所示:

def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        first_name, last_name = self.cleaned_data["fullname"].split()
        user.first_name = first_name
        user.last_name = last_name
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

注意:您应该为全名字段添加一个干净的方法,以确保输入的全名仅包含两部分:名字和姓氏,并且包含其他有效字符。

用户模型参考源代码:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py#L201

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:

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 = "First name")

    class Meta:
        model = User
        fields = ("username", "fullname", "email", )

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:

def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        first_name, last_name = self.cleaned_data["fullname"].split()
        user.first_name = first_name
        user.last_name = last_name
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

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:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py#L201
暮光沉寂 2024-11-09 10:23:15

您必须重写 UserCreationForm.save() 方法:

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.fullname = self.cleaned_data["fullname"]
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

http://code.djangoproject。 com/browser/django/trunk/django/contrib/auth/forms.py#L10

You have to override UserCreationForm.save() method:

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.fullname = self.cleaned_data["fullname"]
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/forms.py#L10

甜心小果奶 2024-11-09 10:23:15

django 1.10 中,这是我在 admin.py 中编写的内容,将 first_nameemaillast_name 添加到 < strong>默认 django 用户创建表单

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib import admin
from django.contrib.auth.models import Group, User

# first unregister the existing useradmin...
admin.site.unregister(User)

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    fieldsets = (
    (None, {'fields': ('username', 'password')}),
    ('Personal info', {'fields': ('first_name', 'last_name', 'email',)}),
    ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    ('Important dates', {'fields': ('last_login', 'date_joined')}),)
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')}),)
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    filter_horizontal = ('groups', 'user_permissions',)

# Now register the new UserAdmin...
admin.site.register(User, UserAdmin)

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

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib import admin
from django.contrib.auth.models import Group, User

# first unregister the existing useradmin...
admin.site.unregister(User)

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    fieldsets = (
    (None, {'fields': ('username', 'password')}),
    ('Personal info', {'fields': ('first_name', 'last_name', 'email',)}),
    ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    ('Important dates', {'fields': ('last_login', 'date_joined')}),)
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')}),)
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    filter_horizontal = ('groups', 'user_permissions',)

# Now register the new UserAdmin...
admin.site.register(User, UserAdmin)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文