【问题标题】:Create parent and child model in one form django以一种形式创建父子模型 django
【发布时间】:2021-12-26 09:21:30
【问题描述】:

我正在尝试构建一个表单来创建具有 RecipeRecipeIngredient 模型的配方,但是当用户创建配方时,我如何让它们以相同的形式出现,因为 RecipeIngredient 依赖于尚未初始化的Recipe的外键?我是否需要在每次用户访问创建页面时都创建一个空白配方才能实现这一点?

models.py:

class Recipe(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='image/', blank=True, null=True)
    name = models.CharField(max_length=220) # grilled chicken pasta
    description = models.TextField(blank=True, null=True)

class RecipeIngredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    name = models.CharField(max_length=220) # grilled chicken pasta
    description = models.TextField(blank=True, null=True)

【问题讨论】:

    标签: python django forms foreign-keys


    【解决方案1】:

    使用formsetformset 是一个抽象层,用于在同一页面上处理多个表单。

    查看官方文档的example

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多