简体   繁体   English

以一种形式创建父子模型django

[英]Create parent and child model in one form django

I am trying to build a form to create a recipe with a Recipe and RecipeIngredient model but when a user is creating a recipe how do I have them both in the same form since RecipeIngredient is dependent on the the foreign key of Recipe which is not yet initialized?我正在尝试构建一个表单来创建一个带有RecipeRecipeIngredient模型的Recipe ,但是当用户创建一个配方时,我如何将它们都以相同的形式存在,因为RecipeIngredient依赖于 Recipe 的外键,目前还没有初始化? Do I need to create a blank recipe everytime a user visits a create page to make this possible?每次用户访问创建页面时,我是否都需要创建一个空白配方以使这成为可能?

models.py:模型.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)

use formset .使用formset formset is a layer of abstraction to work with multiple forms on the same page. formset是一个抽象层,用于在同一页面上处理多个表单。

check the example of official documentation检查官方文档的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM