表单中的Django DRY函数

时间:2018-07-08 12:57:22

标签: python django django-forms django-rest-framework

在我的 forms.py 中,我必须设置然后清理许多类似的变量。

class FormOne(forms.Form):
    email_field = forms.EmailField(
        required=True,
        max_length=70,
        label=mark_safe("""<i>Enter email address</i>"""))

    # other fields

    def clean_email_field(self):
        return data

class FormTwo(forms.Form):
    email_field = forms.EmailField(
        required=True,
        max_length=70,
        label=mark_safe("""<i>Enter email address</i>"""))

    # other fields

    def clean_email_field(self):
        return data

在我的 views.py 中,我可以在文件底部成功定义一个函数,并在上面的代码中引用它。但是,如果我尝试在文件底部放置这样的内容:

def clean_email_field(form_data):
    # rest of function

然后我得到错误:

***ERROR*** clean_email_field undefined

是因为表单是类,而不是defs?

1 个答案:

答案 0 :(得分:1)

如果您想在电子邮件字段中包含其他验证,则可以编写custom validator,然后将其包含在form field中。例如:

from django import forms
from django.core.exceptions import ValidationError

def validate_contains_something(value):
    if 'something' not in value:
        raise ValidationError('no 'something' found')

class FormTwo(forms.Form):
    email_field = forms.EmailField(
        required=True,
        max_length=70,
        label=mark_safe("""<i>Enter email address</i>"""),
        validators=[
            validate_contains_something,
        ])

您甚至可以使用自定义验证器作为默认字段来编写自定义字段(如this example in the docs所示):

class CustomEmailField(forms.EmailField):
    def __init__(self, *args, **kwargs):
        super().__init__(
            *args,
            required=True,
            max_length=70,
            label=mark_safe("""<i>Enter email address</i>"""),
            validators=[
                validate_contains_something,
            ],
            **kwargs)

class CustomEmailField2(forms.EmailField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('required', True)
        kwargs.setdefault('max_length', 70)
        kwargs.setdefault('label', mark_safe("""<i>Enter email address</i>"""))
        kwargs.setdefault('validators', [validate_contains_something, ])
        super().__init__(*args, **kwargs)

这种方法可能是只编写一次验证逻辑的简便方法。