Django:ModelMultipleChoiceField不会保存数据

时间:2011-01-13 19:57:54

标签: django forms manytomanyfield django-forms

我的modelform有一个带有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)

1 个答案:

答案 0 :(得分:8)

您在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
  }