重用Django中的表单字段

时间:2015-01-18 11:30:39

标签: python django django-forms

这个问题在这里被问到:Django: Reuse form fields without inheriting?

虽然,接受的答案很明确,但是如果我想覆盖许多表单方法,它不是很方便。

多数投票的答案有点困难,而且不起作用。

那么,在有或没有继承的情况下,将相同字段包含在多个表单(表单或ModelForms)中的清晰和pythonic方法是什么?

例如,我希望以下课程可以重复使用。

class SetPasswordMixin(forms.Form):

password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput(attrs={'placeholder': _('Password')}))
password2 = forms.CharField(label=_('Password confirmation'),
                            widget=forms.PasswordInput(attrs={'placeholder': _('Password confirmation')}))

def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(_("Passwords don't match"))
    return password2

2 个答案:

答案 0 :(得分:2)

您可以使用多重继承组合两个表单:

class SetPasswordMixin(forms.Form):
    ...

class MessageFormBase(forms.ModelForm):
    class Meta:
        model = Message

class MessageForm(MessageFormBase, SetPasswordMixin):
    pass

答案 1 :(得分:-1)

我刚刚制作了一个解决此问题的代码片段而没有继承:

https://djangosnippets.org/snippets/10523/

它使用了酥脆的形状,但可以使用相同的想法而没有酥脆的形式。我们的想法是在同一个表单标签下使用多个表单。