Django用户模型电子邮件字段:如何强制使用它

时间:2011-03-30 22:13:25

标签: django model

我需要强制使用Django User模型中的电子邮件字段。对我来说,如何做到这一点并不明显。建议欢迎。我目前正在使用:

from django.contrib.auth.forms import UserCreationForm

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

相结合

伊恩

3 个答案:

答案 0 :(得分:18)

您应该能够对提供的注册表单进行子类化,并覆盖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

答案 1 :(得分:6)

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')

答案 2 :(得分:0)

在模型中使用<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

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