Django inlineformset不保存ForeignKey字段

时间:2014-07-16 03:31:42

标签: python django inline-formset

所以我正在测试Django中的inlineformset功能,到目前为止还有以下代码:

应用程序名称:示例

models.py

from django.db import models
from django.core.urlresolvers import reverse

class Recipe(models.Model):
    pub_date = models.DateTimeField('Date Published', auto_now_add= True)
    title = models.CharField(max_length=200)
    instruction = models.TextField()

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('recipe_edit', kwargs={'pk': self.pk})


class Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, related_name="ingredients")
    ingredient = models.CharField(max_length=255)

    def __unicode__(self):
        return self.recipe_id

    def get_absolute_url(self):
        return reverse('ingredient_edit', kwargs={'pk': self.recipe_id})

forms.py

from django import forms
from models import Recipe, Ingredient
from django.forms.models import inlineformset_factory

MAX_INGREDIENTS = 5

IngredientFormSet = inlineformset_factory(
    Recipe,
    Ingredient,
    can_delete=False,
    extra=MAX_INGREDIENTS
)


class UserSubmittedRecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        exclude = ('pub_date',)

views.py

def recipe_create(request, template_name='example/recipe_form.html'):
    if request.POST:
        form = UserSubmittedRecipeForm(request.POST)
        if form.is_valid():
            recipe = form.save(commit=False)
            ingredient_formset = UserSubmittedRecipeForm(request.POST, instance=recipe)
            if ingredient_formset.is_valid():
                recipe.save()
                ingredient_formset.save()
                return redirect('recipe_list')
    else:
        form = UserSubmittedRecipeForm()
        ingredient_formset = IngredientFormSet(instance=Recipe())
    return render(request, template_name, {
        "form": form,
        "ingredient_formset": ingredient_formset
    }, context_instance=RequestContext(request))

观看版本2 这也不起作用。

def recipe_create(request, template_name='example/recipe_form.html'):
    if request.POST:
        form = UserSubmittedRecipeForm(request.POST)
        if form.is_valid():
            created_recipe = form.save()
            ingredient_formset = UserSubmittedRecipeForm(request.POST, instance=created_recipe)
            if ingredient_formset.is_valid():
                ingredient_formset.save()
                return redirect('recipe_list')
    else:
        form = UserSubmittedRecipeForm()
        recipe = Recipe()
        ingredient_formset = IngredientFormSet(instance=recipe)
    return render(request, template_name, {
        "form": form,
        "ingredient_formset": ingredient_formset
    }, context_instance=RequestContext(request))

我遇到的问题是"成分"每次提交表单时,都不会保存Ingredient模型中的字段。

没有显示错误。 Recipe模型中的其余字段可以正确保存。

有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:1)

第2版视图中存在拼写错误。检查这是否解决了您的问题

Views.py第2版:

   def recipe_create(request, template_name='example/recipe_form.html'):
    if request.POST:
        form = UserSubmittedRecipeForm(request.POST)
        if form.is_valid():
            created_recipe = form.save()
            #There was a typo here
            ingredient_formset = IngredientFormSet(request.POST, instance=created_recipe)
            if ingredient_formset.is_valid():
                ingredient_formset.save()
                return redirect('recipe_list')
    else:
        form = UserSubmittedRecipeForm()
        recipe = Recipe()
        ingredient_formset = IngredientFormSet(instance=recipe)
    return render(request, template_name, {
        "form": form,
        "ingredient_formset": ingredient_formset
    }, context_instance=RequestContext(request))

答案 1 :(得分:1)

应该
ingredient_formset = UserSubmittedRecipeForm(request.POST, instance=created_recipe)

ingredient_formset = IngredientFormSet(request.POST, instance=created_recipe)

如果这是问题所在,您已在两个视图中完成。