Django super __init__导致m2m表单无法验证

时间:2010-11-26 08:34:48

标签: django django-forms django-orm

我有一个在验证中处理m2m请求的表单。

我的表格如下

class HuntingReportForm(ModelForm):
    date_travel_started = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2010)))
    date_travel_ended = forms.DateField(widget=extras.SelectDateWidget(years=range(1970,2010)))
    wish_list = forms.ModelMultipleChoiceField(queryset=Specie.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False), required=False)
    bag_list = forms.ModelMultipleChoiceField(queryset=Trophies.objects.all(), widget=FilteredSelectMultiple("verbose name", is_stacked=False), required=False)

class Meta:
    model = HuntingReport
    exclude = ['user',]

def __init__(self, user, *args, **kwargs):
    self.validate = kwargs.pop('validate',False)
    super(HuntingReportForm, self).__init__(*args, **kwargs)

    users = User.objects.filter(userprofile__outfitter=True)
    self.fields['outfitter'].choices = [('', '')] + [(user.pk, user.get_full_name()) for user in users]
    self.fields.keyOrder = ['title', 'report', 'date_travel_started', 'date_travel_ended', 'wish_list', 'bag_list', 'outfitter']

当我删除整个def __init__部分时,表单似乎验证并保存,但是使用以下代码,它只是让我回到页面上说某些字段没有填写,即使它们是

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您不显示视图,但可能是您使用通常的form = HuntingReportForm(request.POST)实例化表单。不幸的是,您已将表单的__init__方法的签名更改为期望user作为第一个位置参数,因此数据未被传入。您应该将user移动到kwargs并将其视为与validate参数相同:

def __init__(self,*args, **kwargs):
    user = kwargs.pop('user', None)
    self.validate = kwargs.pop('validate', False)
    super(HuntingReportForm, self).__init__(*args, **kwargs)