I'm trying to create a simple "recipe" form with a title and a list of 
ingredients, which allows a user to add additional ingredients to the 
recipe.

I'm struggling, however, to implement this in Django. Particularly how to 
associate a formset with a field in a form. I'm sure it's a simple solution 
and one that's been done many times, but I must be missing something.

I've got a model called Recipe that has a 1:n relationship with Ingredient. 
That means, a Recipe can have many Ingredients, but an Ingredient can only 
belong to 1 Recipe.

*models.py:*

class Recipe(models.Model):

    title = models.CharField(blank=True, null=True, max_length=100)


class Ingredient(models.Model):

    title = models.CharField(blank=True, null=True, max_length=1000)
    recipe = models.ForeignKey(Recipe)

The next step would be to set up model forms using the above 2 Models, 
which I've done.

*forms.py:
*
class IngredientForm(forms.ModelForm):
    class Meta:
        model = Ingredient

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

I know I now need to use formset_factory in order to display a list of 
Ingredients. This is where I'm stuck.

*views.py*

from django.forms.formsets import formset_factory

# This obviously just gives me a Recipe form
recipe_form = RecipeForm(request.POST or None)

# This gives me a list of Ingredient forms in a formset, which is what I 
want, but I would like it to be associated with a Recipe
ingredient_formset = formset_factory(IngredientForm)

The above 2 lines of code will give the IngredientForm and RecipeForm as 
two separate forms that I can send to the template. However, there must be 
a way to display the recipe_form so that it displays the ingredient_formset 
as a "field" of a recipe_form. Subsequently, the user should be able to add 
extra ingredients to the recipe.

I've had a read of the django documentation and haven't been able to come 
across anything there. Is there a particular section of the django docs 
that I should be focusing my attention on to get me unstuck? Or is there 
another way I should be approaching this?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to