django-bootstrap-modal-forms icon indicating copy to clipboard operation
django-bootstrap-modal-forms copied to clipboard

Saving instance twice (couldn't resolve with other issues open)

Open nmacchitella opened this issue 3 years ago • 1 comments
trafficstars

I am implementing a django-bootstrap-modal-forms 2.2.0 on my django app but I am having a problem. Every time I submit the modal form, the instance is created twice.

I read that it is expected to have two post requests...the issue is that I am doing a few things on the form before saving it (adding many to many values) and as I am trying to override the save function now it ends up saving the model twice.


class NewDirectorView(BSModalCreateView):
    template_name = 'action/forms/DirectorModelForm.html'
    form_class = DirectorModelForm
    success_message = 'Success: Director was created.'
    success_url = reverse_lazy('action:new_jobproject')

    def get_object(self):
        pk = self.kwargs.get('pk')
        director = get_object_or_404(Contact, pk=pk)
        return director

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.owner = self.request.user
        obj.save()
        obj.title.add(Title.objects.get(title_name='Director', title_department='Production'))
        return super().form_valid(form)

nmacchitella avatar Dec 21 '21 11:12 nmacchitella

You might try overwriting the save through forms.py. I was able to resolve the double save issue with sometime similar to this.

from bootstrap_modal_forms.utils import is_ajax

def save(self, commit=True):
    someName = super().save(commit=False)
    if commit and not is_ajax(self.request.META):
        # do stuff
        someName.save()
   return someName

mlongmiresqa avatar Dec 30 '21 19:12 mlongmiresqa