【问题标题】:How can I get the email field in the basic Django User model to be required?如何在需要的基本 Django 用户模型中获取电子邮件字段?
【发布时间】:2012-05-03 03:30:47
【问题描述】:

我试图强制用户在注册时输入他们的电子邮件。我了解如何将表单字段与 ModelForms 一起使用。但是,我无法弄清楚如何强制要求现有字段。

我有以下 ModelForm:

class RegistrationForm(UserCreationForm):
    """Provide a view for creating users with only the requisite fields."""

    class Meta:
        model = User
        # Note that password is taken care of for us by auth's UserCreationForm.
        fields = ('username', 'email')

我正在使用以下视图来处理我的数据。我不确定它的相关性如何,但值得一提的是,其他字段(用户名、密码)正在正确加载并出现错误。但是,用户模型已经根据需要设置了这些字段。

def register(request):
    """Use a RegistrationForm to render a form that can be used to register a
    new user. If there is POST data, the user has tried to submit data.
    Therefore, validate and either redirect (success) or reload with errors
    (failure). Otherwise, load a blank creation form.
    """
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            # @NOTE This can go in once I'm using the messages framework.
            # messages.info(request, "Thank you for registering! You are now logged in.")
            new_user = authenticate(username=request.POST['username'], 
                password=request.POST['password1'])
            login(request, new_user)
            return HttpResponseRedirect(reverse('home'))
    else:
        form = RegistrationForm()
    # By now, the form is either invalid, or a blank for is rendered. If
    # invalid, the form will sent errors to render and the old POST data.
    return render_to_response('registration/join.html', { 'form':form }, 
        context_instance=RequestContext(request))

我尝试在 RegistrationForm 中创建一个电子邮件字段,但这似乎没有任何效果。我是否需要扩展用户模型并覆盖电子邮件字段?还有其他选择吗?

谢谢,

ParagonRG

【问题讨论】:

    标签: python django django-forms modelform


    【解决方案1】:

    只需覆盖 __init__ 以使电子邮件字段成为必填项:

    class RegistrationForm(UserCreationForm):
        """Provide a view for creating users with only the requisite fields."""
    
        class Meta:
            model = User
            # Note that password is taken care of for us by auth's UserCreationForm.
            fields = ('username', 'email')
    
        def __init__(self, *args, **kwargs):
            super(RegistrationForm, self).__init__(*args, **kwargs)
            self.fields['email'].required = True
    

    这样,您不必完全重新定义字段,只需更改属性即可。希望对您有所帮助。

    【讨论】:

    • 太棒了!这似乎行得通。我没有意识到有一个“必需的”属性。在此示例中,您究竟覆盖了哪个 init? UserCreationForm 的 init 函数,它最终(通过一些父级)继承 ModelForm 类?
    • 我也发现了这个 StackOverflow 问题,它提供了一个非常相似的问题的答案:stackoverflow.com/questions/1134667/…
    • 我不是解释对 super 的调用的最佳人选,但简而言之,__init__ 方法执行UserCreationForm 中定义的所有操作,然后它执行@987654326 中定义的所有操作@
    • 是的。我知道__init__ 函数的作用,并且它们可以覆盖它们的父函数。然而,我没有意识到在这种情况下这是可能的。感谢您的帮助!
    猜你喜欢
    • 2019-01-13
    • 2021-01-07
    • 2010-11-12
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多