在Djang中重用表单域

2024-03-29 08:51:14 发布

您现在位置:Python中文网/ 问答频道 /正文

有人问这个问题:Django: Reuse form fields without inheriting?

虽然,公认的答案是明确的,但它不是很方便,如果我想重写许多表单方法。在

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

那么,在继承或不继承的情况下,将相同的字段包含到多个表单(表单或ModelForms)中的清晰而python方法是什么呢?在

例如,我希望下面的类是可重用的。在

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

Tags: 方法答案self表单formspasswordwidgetattrs
2条回答

我刚刚制作了一个片段,在不继承的情况下解决了这个问题:

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

它使用的是酥脆的形式,但同样的想法也可以在没有酥脆形式的情况下使用。其思想是在同一个表单标记下使用多个表单。在

可以使用多重继承组合两个窗体:

class SetPasswordMixin(forms.Form):
    ...

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

class MessageForm(MessageFormBase, SetPasswordMixin):
    pass

相关问题 更多 >