使Form和ModelForm都可以从FormMixin继承字段

2024-10-02 02:33:40 发布

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

我有一个LocationMixin,它将位置选择器添加到表单中,如下所示。在

class LocationMixin(object):
    location_required = False
    location_label = u'location'
    location_text = forms.CharField(label=u'location', required=False, \
                                    widget=forms.TextInput(attrs={
                                        'class': 'city_input  inputFocus proCityQueryAll proCitySelAll',
                                        'autocomplete': 'off',
                                        'readonly': 'readonly',
                                    }))

    def __init__(self, *args, **kwargs):
        super(LocationMixin, self).__init__(*args, **kwargs)
        if 'location' not in self.fields:
            raise Exception('LocationMixin need form contain field named location !')
        self.fields['location_text'].required = self.location_required
        self.fields['location_text'].label = self.location_label



class ActivateProfileForm(LocationMixin, forms.ModelForm):

    location_required = True

    class Meta:
        model = Member
        fields = ['address', 'car_type', 'car_no', 'location', 'city']
        widgets = {
            'location': HiddenInput(),
            'city': HiddenInput(),
        }

但在这条线上就会被打破:`

self.fields['location_text'].required = self.location_required

Django抱怨location_text不存在于self.fields

^{pr2}$



我必须将class LocationMixin(object):改为class LocationMixin(forms.ModelForm):才能使其工作,而{}不能。

问题是:
我还希望LocationMixinclass SomeForm(LocationMixin, forms.Form)一起工作。在


Tags: textselffalsecityfieldsobjectinitrequired
1条回答
网友
1楼 · 发布于 2024-10-02 02:33:40

你的位置mixin现在不是真正的Django表单。尝试从forms.Form继承,而不是从object继承。在

另外,根据您的目标是什么,您可能需要颠倒主类定义的顺序。这个:

class ActivateProfileForm(LocationMixin, forms.ModelForm):

不同于:

^{pr2}$

相关问题 更多 >

    热门问题