用于manytomy的Django前端内联表单显示为带有add选项的表

2024-10-03 04:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一种方法来添加(和编辑)元素(与M2M连接)在前端(不是管理)的形式。在

我的模型:

class IngredientName(models.Model):
        name = models.CharField(_('name of ingredient'), max_length=255)

class Unit(models.Model):
        name = models.CharField(_('unit name'), unique=True, max_length=255)

class Ingredient(models.Model):
        name = models.ForeignKey(IngredientName)
        unit = models.ForeignKey(Unit)
        value = models.FloatField()

class Recipe(models.Model):
        title = models.CharField(_('title'), max_length=250)
        portions = models.PositiveIntegerField(_('portions'))
        ingredients = models.ManyToManyField(Ingredient)
        description = models.TextField(_('description'))

Forms:

    class RecipeForm(ModelForm):
        class Meta:
            model = Recipe

观点:

^{pr2}$

在第一步中,我尝试使用IngredientFormSet = inlineformset_factory(Ingredient,Recipe, form=RecipeForm),但我遇到了一个错误:

<class 'recipe.models.Recipe'> has no ForeignKey to <class 'recipe.models.Ingredient'>

最好的、可重用的方法是什么?是否存在用于此的小部件?在


Tags: 方法namemodeltitlemodelsrecipeunitlength