我的Django ModelForm是否未绑定?

时间:2018-04-05 09:51:03

标签: python django django-forms django-class-based-views

在过去的几天里,我一直在与CreateView和相应的ModelForm作斗争:我无法获取表单来处理POSTed数据并保存对象。提交数据时,我会收到带有表单的同一页面。

{{ form.errors }}{{ form.non_field_errors }}不会在我的模板中输出任何内容,因此似乎没有任何错误。

我做错了什么?我是否必须手动将数据绑定到表单?

views.py

class CreateFlyerView(CreateView, CookLoginRequired):
    template_name = 'flyer/create.html'
    model = Flyer
    form_class = CreateFlyerForm
    success_url = reverse_lazy('flyer_start')

    def get_form_kwargs(self):
        kwargs = super(CreateFlyerView, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        return kwargs

    def get_context_data(self, **kwargs):
         context = super(CreateFlyerView, self).get_context_data(**kwargs)
         now = datetime.datetime.now()
         meals_as_host = MenuOffer.objects.filter(deleted=False, host=self.request.user).order_by('cdate')
         upcoming_meals_as_host = meals_as_host.filter(eating_time__gte=now).order_by('cdate')[:4]
         past_flyers = Flyer.objects.filter(host=self.request.user, cdate__lt=now)

         context.update({
             'upcoming_meals_as_host': upcoming_meals_as_host,
             'past_flyers': past_flyers,
             'user_images': Image.objects.filter(account=self.request.user),
                 })
         return context

forms.py

class CreateFlyerForm(forms.ModelForm):
    picture = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=Image.objects.all())
    meals = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=MenuOffer.objects.all())
    headline = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Flyer
        fields = ['headline', 'copy', 'avatar', 'style', 'greeting', 'picture', 'meals']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(CreateFlyerForm, self).__init__()
        self.fields['headline'].initial = _(u'Some headline with {}').format(user.neighborhood if user.neighborhood else user.place)
        self.fields['copy'].initial = _(u'Some copy.')
        self.fields['avatar'].initial = user.image
        self.fields['style'].initial = 'MODERN'
        self.fields['greeting'].initial = user.first_name
        self.fields['picture'].queryset = Image.objects.filter(account=user)
        self.fields['meals'].queryset = MenuOffer.objects.filter(deleted=False, host=user, eating_time__gte=datetime.datetime.now()).order_by('cdate')[:4]

1 个答案:

答案 0 :(得分:3)

您忘记将*args**kwargs传递给super()方法中的__init__来电。因此,表单始终使用data=None进行初始化,因此它是一种未绑定的表单。

应该是:

class CreateFlyerForm(forms.ModelForm):
    ...

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