1
我有一个LocationMixin
,它向表单添加一个位置选择器,如下所示。使Form和ModelForm都可以继承FormMixin中的字段
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']需要= 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)
。
请你提供完整的追踪? – Nilesh 2014-09-24 07:41:18