在过去的几天里,我一直在与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]
答案 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)
...