如何使UserCreationForm电子邮件字段成为必需

时间:2016-11-18 19:28:53

标签: django django-forms

我是Django的新手。 我想要子类UserCreationForm中的电子邮件字段是必需的。 我已经尝试了注释方法,但到目前为止还没有。我试过this的解决方案,但无济于事。任何帮助将不胜感激。

class MyRegistrationForm(UserCreationForm):
    captcha = NoReCaptchaField()
    #email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class': 'mdl-textfield__input'}))

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email', 'password')
        #email = {
        #   'required': True
        #}
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
            'last_name': forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
            'username': forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
            #'email': forms.TextInput(attrs={'class': 'mdl-textfield__input'})
        }

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        user.username = self.cleaned_data["username"]
        user.email = self.cleaned_data["email"]
        #user.user_level = self.cleaned_data["user_level"]
        if commit:
            user.save()

        return user

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

        self.fields['password1'].widget.attrs['class'] = 'mdl-textfield__input'
        self.fields['password2'].widget.attrs['class'] = 'mdl-textfield__input'
        #self.fields['email'].required=True

3 个答案:

答案 0 :(得分:1)

这解决了问题:email = forms.CharField(required=True, widget=forms.EmailInput(attrs={'class': 'validate',}))

答案 1 :(得分:1)

将此添加到您的forms.py文件:

class Userform(UserCreationForm):
    email = forms.EmailField(required=True)
    class meta:
         model = User
         fields = ('name','email')

答案 2 :(得分:0)

我检查了Django的User模型,它有required=False。所以,我认为你无法使用默认的用户模型来实现你想要的,基于{34}的note section覆盖默认字段"在django文档中。我已经加入了片段

  

ModelForm是一个可以自动生成特定的常规表单   领域。自动生成的字段取决于   Meta类的内容以及已经存在的字段   以声明方式定义。基本上,ModelForm只会生成字段   表单中缺少的,或者换句话说,没有的字段   以声明方式定义。

     

以声明方式定义的字段保持原样,因此任何字段   对Meta属性(如小部件,标签)进行的自定义   help_texts或error_messages被忽略;这些仅适用于领域   这是自动生成的。

     

同样,以声明方式定义的字段不会绘制其属性   像max_length或相应型号所需。如果你想   要保持模型中指定的行为,必须设置   声明表单字段时明确相关的参数。

     

例如,如果Article模型如下所示:

class Article(models.Model):
    headline = models.CharField(
    max_length=200,
    null=True,
    blank=True,
    help_text='Use puns liberally',
)
content = models.TextField() and you want to do some custom validation for headline, while keeping the blank and help_text values
     

如指定的那样,您可以像这样定义ArticleForm:

class ArticleForm(ModelForm):
    headline = MyFormField(
    max_length=200,
    required=False,
    help_text='Use puns liberally',
)

class Meta:
    model = Article
    fields = ['headline', 'content'] You must ensure that the type of the form field can be used to set the contents of the corresponding
     

模型字段。当它们不兼容时,您将获得ValueError   因为没有发生隐式转换。

所以试试这个,

from django.forms import EmailField
from django.core.validators import EMPTY_VALUES

# I used django [emailfield code][2] as reference for the code of MyEmailField
# Also, following comment in django [custom form fields document][2]:
# If the built-in Field classes don’t meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its __init__() method accept the core arguments mentioned above (required, label, initial, widget, help_text).
# You can also customize how a field will be accessed by overriding get_bound_field().

class MyEmailField(forms.EmailField):

    def __init__(self, *args, **kwargs):
        super(MyEmailField, self).__init__(*args, strip=True, **kwargs)

    # Clean would be called when checking is_clean
    def clean(self,value):
        if value in EMPTY_VALUES:
            raise Exception('Email required')
        value = self.value.strip()
        return super(MyEmailField, self).clean(value)

class MyRegistrationForm(UserCreationForm):
    captcha = NoReCaptchaField()
    # All available arguments listed in django [core fields argument document][2]. Currently they are required, label, label_suffix, initial, widget, help_text, error_messages, validators, localize, disabled
    email = MyEmailField(required=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email', 'password')
        # other part of your code

PS:我没有测试过这段代码,但根据文档,我认为这应该会让你朝着一个良好的方向发展。

更多参考文献:
Django auth.user with unique email
How to make email field unique in model User from contrib.auth in Django
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html