我有一个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'] .require = self.location_required
Django抱怨location_text
中不存在self.fields
:
Traceback (most recent call last):
File "E:\Python27\lib\site-packages\django\core\handlers\base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Incubations\Project\xxx\src\xxx\decorator.py", line 54, in wrapper
return func(request, *args, **kwargs)
File "D:\Incubations\Project\xxx\src\xxx\views_member.py", line 166, in activate_profile
form = ActivateProfileForm(instance=member)
File "D:\Incubations\Project\xxx\src\location_selector\forms.py", line 25, in __init__
self.fields['location_text'].required = self.location_required
KeyError: 'location_text'
我必须将class LocationMixin(object):
更改为class LocationMixin(forms.ModelForm):
才能使其正常工作,class LocationMixin(forms.BaseForm)
无法正常工作。
问题是:
我还希望LocationMixin
与class SomeForm(LocationMixin, forms.Form)
一起使用。
答案 0 :(得分:0)
您的LocationMixin现在不是真正的Django表单。尝试继承forms.Form
而不是对象。
此外,根据您的目标,您可能需要颠倒主类定义的顺序。这样:
class ActivateProfileForm(LocationMixin, forms.ModelForm):
不同于:
class ActivateProfileForm(forms.ModelForm, LocationMixin):