0

我试图强制用户在注册时输入他们的电子邮件。我了解如何将表单字段与 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 中创建一个电子邮件字段,但这似乎没有效果。我是否需要扩展用户模型并覆盖电子邮件字段?还有其他选择吗?

谢谢,

典范RG

4

1 回答 1

2

只需覆盖__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

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

于 2012-04-22T04:31:19.020 回答