【问题标题】:Django User model email field: how to make it mandatoryDjango用户模型电子邮件字段:如何使其成为强制性
【发布时间】:2011-07-26 11:19:57
【问题描述】:

我需要将 Django 用户模型中的电子邮件字段设为必填项。如何做到这一点对我来说并不明显。欢迎提出建议。我目前正在使用:

from django.contrib.auth.forms import UserCreationForm

用于我的用户创建表单,并将其与我自己的自定义 UserProfileCreateForm 结合起来

伊恩

【问题讨论】:

  • 你应该接受他的回答。

标签: django model


【解决方案1】:

您应该能够对提供的注册表单进行子类化并覆盖Meta 类中字段的属性。

from django.contrib.auth.forms import UserCreationForm

# Not sure about the syntax on this one. Can't find the documentation.
class MyUserCreationForm(UserCreationForm):

    class Meta:
        email = {
            'required': True
        }


# This will definitely work
class MyUserCreationForm(UserCreationForm):

    def __init__(self, *args, **kwargs):
        super(MyUserCreationForm, self).__init__(*args, **kwargs)

        self.fields['email'].required = True

【讨论】:

  • 第一个解决方案对我不起作用。第二种解决方案效果很好。非常感谢。
  • 可以直接在模型上做吗?
【解决方案2】:
from django import forms
from django.contrib.auth.models import User


class MyUserForm(forms.ModelForm):

    email = forms.CharField(max_length=75, required=True)

    class Meta:

        model = User
        fields = ('username', 'email', 'password')

【讨论】:

  • 可以直接在模型上做吗?
【解决方案3】:

在你的模型中使用EmailField

查看更多信息 https://docs.djangoproject.com/en/2.1/ref/models/fields/#emailfield

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-01-13
    • 2010-11-12
    • 2012-05-03
    • 2010-10-29
    • 2020-12-31
    相关资源
    最近更新 更多