How to make a form that creates a new object and objects related by foreign keys in one request?

StackOverflow https://stackoverflow.com/questions/23280719

  •  09-07-2023
  •  | 
  •  

Вопрос

I have a Recipe model and a Step model, where multiple steps are linked to a recipe via a foreign key. What is the best solution for making a form that creates a new recipe and multiple steps at the same time? After googling around I have only found inline formsets, but they require an instance of the recipe (found by pk) but of course in practice the recipe would not be saved before the form is generated since they (the recipe and its steps) are created in one request. Anyone solved a problem similar to this?

Это было полезно?

Решение

Inline formsets are indeed the way you want to go. You'll want to do something along the lines of:

def add_recipe(request):
    if request.method == 'POST':
        form = RecipeForm(data=request.POST)
        if form.is_valid():
            recipe = form.save(commit=False)
            steps_formset = StepsFormSet(data=request.POST, instance=recipe)
            if steps_formset.is_valid():
                recipe.save()
                steps_formset.save()
        else:
            steps_formset = StepsFormSet(data=request.POST)
    else:
        form = RecipeForm()
        steps_formset = StepsFormSet()
    return render(request, 'recipe_entry.html', {'form': form, 'steps_formset': steps_formset})
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top