If I create a formset using modelformset_factory like this:
IngredientFormSet = modelformset_factory(RecipeIngredients, form=RecipeIngredientsForm)
formset = IngredientFormSet(request.POST)
and my form looks like this
class RecipeIngredientsForm(forms.ModelForm):
Ingredient = forms.CharField(max_length= 100)
class Meta:
model = RecipeIngredients
exclude = ('weightmetric','recipe')
Where would I put my custom .save() method? Would I put it under the RecipeIngredientsForm?
[a potential solution]
In your view do something like this:
if formset.is_valid():
for form in formset:
obj = form.save(commit=False) #obj = RecipeIngredient model object
try:
ingredient_in_db = Ingredient.objects.get(name = form.cleaned_data.get('ingredientform'))
except:
ingredient_in_db = None
if ingredient_in_db:
obj.ingredient = ingredient_in_db
else:
new_ingredient = Ingredient.objects.create(name = form.cleaned_data.get('ingredientform'))
obj.ingredient = new_ingredient
obj.recipe = recipeobj
obj.save()
Incidentally, I think this method would also allow me to do a custom .save(), given that I take each form in the formset and do a form.save(commit= False) on it. It was easier though, to just do it in my view, since I needed access to the recipe object.
I’m not sure of the best way to override the existing
save()method on the BaseModelForm. My guess is that you actually would want to either:Create your own field that has it’s own
to_python()method which will take the text and find/create the associated object.Use save(commit=False) on the formset, do the ingredient lookup/creation, and then commit afterwards