Home > Software design >  Create parent and child model in one form django
Create parent and child model in one form django

Time:11-15

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? Do I need to create a blank recipe everytime a user visits a create page to make this possible?

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)

CodePudding user response:

use formset. formset is a layer of abstraction to work with multiple forms on the same page.

check the example of official documentation

  • Related