如何在django-registration中子类化注册表单

时间:2014-01-08 19:10:21

标签: django django-registration

我希望用户同意服务条款并支持唯一的电子邮件。 django-registration有两种不同的子类注册表单:RegistrationFormTermsOfServiceRegistrationFormUniqueEmail

我是否必须制作自己的RegistrationForm子级,然后提供这些功能?如果是这样,这将如何实现?注册表格会在我的应用程序的forms.py或其他地方生效吗?

1 个答案:

答案 0 :(得分:2)

快速浏览两个班级的source

class RegistrationFormTermsOfService(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.

    """
    tos = forms.BooleanField(widget=forms.CheckboxInput,
                             label=_(u'I have read and agree to the Terms of Service'),
                             error_messages={'required': _("You must agree to the terms to register")})


class RegistrationFormUniqueEmail(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which enforces uniqueness of
    email addresses.

    """
    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.

        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
        return self.cleaned_data['email']

正如您所看到的,这两个类不会覆盖另一个类定义的方法,因此您应该只能将自己的类定义为:

from registration.forms import RegistrationFormUniqueEmail, RegistrationFormTermsOfService
class RegistrationFormTOSAndEmail(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
    pass

它应该起作用,但我还没有测试过。至于这个班级的位置; forms.py是一个很好的位置。

更新

https://django-registration.readthedocs.org/en/latest/views.html稍微阅读一下,告诉我们可以通过url定义传递视图中的一些参数;例如表格类。 只需使用以下网址:

url(r'^register/$',
    RegistrationView.as_view(form_class=RegistrationFormTOSAndEmail), 
    name='registration_register')