inlineformset_factory create new objects and edit objects after created

前端 未结 4 1413
说谎
说谎 2020-12-13 07:53

In the django docs, there\'s an example of using inlineformset_factory to edit already created objects

https://docs.djangoproject.com/en/dev/topics/forms/mo

4条回答
  •  难免孤独
    2020-12-13 08:07

    I didn't read your question properly at first. You need to also render the the form for the parent model. I haven't tested this, I'm going off what I've done before and the previously linked answer, but it should work.

    UPDATE

    If you're using the view to both and edit, you should check for an Author ID first. If there's no ID, it'll render both forms as a new instance, whereas with an ID it'll, fill them with the existing data. Then you can check if there was a POST request.

    def manage_books(request, id):
    
        if id:
            author = Author.objects.get(pk=author_id)  # if this is an edit form, replace the author instance with the existing one
        else: 
            author = Author()
        author_form = AuthorModelForm(instance=author) # setup a form for the parent
    
        BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))
        formset = BookInlineFormSet(instance=author)
    
        if request.method == "POST":
            author_form = AuthorModelForm(request.POST)
    
            if id: 
                author_form = AuthorModelForm(request.POST, instance=author)
    
            formset = BookInlineFormSet(request.POST, request.FILES)
    
            if author_form.is_valid():
                created_author = author_form.save(commit=False)
                formset = BookInlineFormSet(request.POST, request.FILES, instance=created_author)
    
                if formset.is_valid():
                    created_author.save()
                    formset.save()
                    return HttpResponseRedirect(created_author.get_absolute_url())
    
        return render_to_response("manage_books.html", {
            "author_form": author_form,
            "formset": formset,
        })
    

提交回复
热议问题