How to add items into a ModelForm that contains a ForeignKey

I have three models: Recipe, Ingredient, and RecipeIngredient.

I created a ModelForm for Recipe with a FormSet for RecipeIngredient.

Django generates a Select box with the items to choose for ingredients. However, what if I want the user to add a new ingredient at the same time without having to go into another form to add an ingredient?

My idea was to convert the Select widget to a TextInput and then leverage get_or_create. However, I get validation errors unless I enter the FK (i.e. 1) in the TextInput.

Any suggestions for a very new beginner to Django?

Yes - don’t try to do it that way.

Yes it can be done, but if you notice how the Django Admin works, it doesn’t try to do it that way.

Notice how it uses a green “+” icon next to the selection box to allow for the entry of a new related field, and then updates the base form.

As a first project of this nature, that’s what my suggestion would be. (Get the easier solution working first, then make it as fancy as desired.)

Thanks for the advice. Would it be hard to get the green plus inside my model by taking some code from the admin? Perhaps a reference you could point me to? My searches thus far shows only to add it to a custom admin model but not in a form.

Again, go simple first while you’re working everything else out.

Put a “+” icon on the page that is just a link to an “add an entry” page. Then set the success_url on that page to return you to this one.

Once you have all that working, then you can change it to an AJAX call that retrieves the “add an entry” template as a fragment to use as a modal dialog if that’s the way you want to go.