2014-09-24 67 views
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)

+0

请你提供完整的追踪? – Nilesh 2014-09-24 07:41:18

回答

0

您的LocationMixin现在不是真正的Django表单。尝试继承forms.Form而不是对象。

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

class ActivateProfileForm(LocationMixin, forms.ModelForm): 

不同于:

class ActivateProfileForm(forms.ModelForm, LocationMixin):