gpt4 book ai didi

python - 我的 Django ModelForm 是未绑定(bind)的吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:25 25 4
gpt4 key购买 nike

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

{{ form.errors }}{{ form.non_field_errors }} 在我的模板中没有输出任何东西,所以似乎没有任何错误.

我做错了什么?我必须手动将数据绑定(bind)到表单吗?

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

表单.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]

最佳答案

您忘记传递 *args**kwargssuper()调用__init__方法。因此,表单总是用 data=None 初始化。所以它是一个未绑定(bind)的表单。

应该是:

class CreateFlyerForm(forms.ModelForm):
...

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

关于python - 我的 Django ModelForm 是未绑定(bind)的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com