inline formset only save the last form

后端 未结 1 1416
情深已故
情深已故 2021-01-26 18:19

i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form , my models.py

class Book(mo         


        
1条回答
  •  不知归路
    2021-01-26 18:52

    It is several years since I did any work on Django but I will have a go at annotating your code and adding my thoughts.

    def form_valid(self,form):
        context = self.get_context_data() # This line looks fine
        context = context['book'] # You are overwriting your context here, call this 
        with transaction.atomic():
            self.object = form.save() # Your have a save here and one further down, this is also setting self object which may be incorrect.
            if context.is_valid():
                context.instance = self.object
                context.save()
        return super(CreateBookView,self).form_valid(form)
    

    Like I said, I haven't done any Django in several years, so I am just referring to some of my old code (which may be outdated) from https://github.com/timhughes/django-cbv-inline-formset/blob/master/music/views.py#L26 which I will annotate with comments.

    def form_valid(self, form):
        context = self.get_context_data(form=form)  # Get the context data for the form in question.
        formset = context['track_formset']  # Extract the formset out of the context.
        if formset.is_valid():  # Validate the formset is valid
            response = super().form_valid(form)  # Call the parent class's form_valid.
            formset.instance = self.object  # Set the formsets type (instance of self.object) so that django knows how to save it.
            formset.save()  # Save the formset here
            return response  # Send a response to the user
        else:
            return super().form_invalid(form) # Send a response to the user with invalid form information.
    

    0 讨论(0)
提交回复
热议问题