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)
use formset
. formset
is a layer of abstraction to work with multiple forms on the same page.
check the example of official documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.