gpt4 book ai didi

Django:ModelMultipleChoiceField 不会保存数据

转载 作者:行者123 更新时间:2023-12-02 07:12:19 24 4
gpt4 key购买 nike

我的模型表单有一个带有 ModelMultipleChoiceField 的字段,该字段具有到 Category 对象的查询集。问题是表单提交,但类别数据没有保存。想法?

非常感谢!

表格:

class MealForm(forms.ModelForm):
class Meta:
model = Meal
fields = ('category','date','time')

category = forms.ModelMultipleChoiceField(
label=_("Food style"),
queryset=Category.objects.all(),
required=True)

查看
@login_required
def new_meal(request, template_name="meal/newmeal.html"):

if request.method == 'POST':
form = MealForm(request.POST)
form.mom = request.user
if form.is_valid():
meal = form.save(commit=False)
meal.mom = request.user
meal.save()
return HttpResponseRedirect('/meal/%d' % meal.id )
else:
form = MealForm()

data = {
'form': form,
'add': True
}

型号:
class Category(models.Model):

name = models.CharField(default='',max_length=100)
num_tags = models.IntegerField(default=0)

def __unicode__(self):
return "%s" % self.name
class Meta:
ordering = ['name']

class Meal(models.Model):
category = models.ManyToManyField(Category)

最佳答案

您需要使用 mymodelform.save_m2m()当您这样做时 commit=False在您的 ModelForm因为没有 ID(又名 save(commit=True))就无法保存 m2m 关系。

如果未先保存父模型,则中间表 (m2m) 没有可引用的 ID!

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

@login_required
def new_meal(request, template_name="meal/newmeal.html"):

if request.method == 'POST':
form = MealForm(request.POST)
form.mom = request.user
if form.is_valid():
meal = form.save(commit=False)
meal.mom = request.user
meal.save()
form.save_m2m() # save m2m after meal has id

return HttpResponseRedirect('/meal/%d' % meal.id )
else:
form = MealForm()

data = {
'form': form,
'add': True
}

关于Django:ModelMultipleChoiceField 不会保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684618/

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