使用inlineformset工厂克隆和编辑对象

时间:2017-05-11 07:00:15

标签: django inline-formset

我有三个型号,即。 Item,RecipeIngredient和Recipe看起来像这样:

模型 - RecipeIngredient

class RecipeIngredient(models.Model):
    item = models.ForeignKey(Item)
    recipe = models.ForeignKey(Recipe)
    item_quant = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    sub_recipe = models.ForeignKey(
       Recipe, blank=True, null=True,
       related_name="sub_recipe"
    )

    class Meta:
       verbose_name = _("Recipe Ingredient")
       verbose_name_plural = _("Recipe Ingredients")
       unique_together = (('item', 'recipe'),)

模型 - 食谱

class Recipe(models.Model):
    name = models.CharField(
        max_length=128,
    )
    num_servings = models.IntegerField()

    class Meta:
       verbose_name = 'Recipe'
       verbose_name_plural = 'Recipies'

模型 - 项目

    class Item(models.Model):
        name = models.CharField(
            max_length=128
        )

我有RecipeCreateView,我使用inlineformset_factory来创建配方和相应的成分。

我在RecipeListView中有一个功能来克隆配方。 我在这里做的是我正在重定向到具有要克隆的配方的id的创建视图URL。

RecipeCreateView -

    class RecipeCreateView(InventoryEditMixin, CreateView):
        model = Recipe
        form_class = RecipeForm
        template_name = 'inventory/recipe_add.html'
        formset_class = RecipeIngredientFormSet

        def get_initial(self):
        clone_recipe = self.request.GET.get('clone_recipe')
        if clone_recipe:
            recipe = Recipe.objects.filter(id=clone_recipe).first()
            if recipe:
                self.initial.update({'num_servings': recipe.num_servings})

        return self.initial

InventoryEditMixin下,我使用get_context_data使用查询集初始化inlineformset_factory。

    def get_context_data(self, **kwargs):
        clone_recipe = self.request.GET.get('clone_recipe')
        if clone_recipe:
            recipe = Recipe.objects.get(id=clone_recipe)
            ingredients = RecipeIngredient.objects.filter(
                recipe__id=clone_recipe)
            if recipe:
                context['formset'] = RecipeIngredientFormSet(
                    queryset=ingredients,
                )

        return context

这不是初始化formset。无法弄清楚原因。

顺便说一句,我的inlineformset_factory看起来像这样:

    RecipeIngredientFormSet = inlineformset_factory(
        Recipe,
        RecipeIngredient,
        fk_name='recipe',
        form=RecipeIngredientForm,
        formset=BaseRecipeFormSet,
        can_order=False,
        can_delete=True, extra=1,
        fields=('id',
                'item',
                'item_quant'))

任何想法,我该如何初始化?

0 个答案:

没有答案
相关问题