Creating a model and related models with Inline formsets

前端 未结 3 1201
独厮守ぢ
独厮守ぢ 2020-11-28 01:50

[I have posted this at the Django users | Google Groups also.]

Using the example in the inline formset docs, I am able to edit objects belo

3条回答
  •  温柔的废话
    2020-11-28 02:11

    I'd actually like to propose a small adjustment to nbv4's solution:

    Assume that you don't create the empty created_author outside of the if-else statement and thus need to nest the formset inside the author_form.is_valid() to avoid runtime errors when the author_form is not valid (and thus no created_author is instantiated).

    Instead of:

    if request.method == 'POST':
        author_form = AuthorModelForm(request.POST)
        if author_form.is_valid():
            created_author = author_form.save()
            formset = BookFormSet(request.POST, instance=created_author)
            if formset.is_valid():
                formset.save()
                return HttpResponseRedirect(...)
    else:
        ...
    

    Do the following:

    if request.method == 'POST':
        author_form = AuthorModelForm(request.POST)
        if author_form.is_valid():
            created_author = author_form.save(commit=False)
            formset = BookFormSet(request.POST, instance=created_author)
            if formset.is_valid():
                created_author.save()
                formset.save()
                return HttpResponseRedirect(...)
    else:
        ...
    

    This version avoids committing the created_author until the book_formset has had a chance to validate. The use case to correct for is that someone fills out a valid AuthorForm with an invalid BookFormSet and keeps resubmitting, creating multiple Author records with no Books associated with them. This seems to work for my project-tracker app (replace "Author" with "Project" and "Book" with "Role").

提交回复
热议问题