Reputation: 592
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 a many to many value) and as I am trying to override the save function now it ends up saving the model twice.
class DirectorModelForm(BSModalModelForm):
class Meta:
model = Contact
exclude = ['owner', 'matching_user', 'id', 'referral', 'name_surname','title','city']
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)
Upvotes: 0
Views: 587
Reputation: 11
As Foocli explained here, the thing is that django-bootstrap-modal-forms performs an additional ajax request to the same url to validate the form. So, all related functions are actually called twice, but in the package, saving the instance during an ajax request is prevented in form's save method. And in your code, you call obj.save()
in view's form_valid, and it is performed twice.
Consider wrapping your additional actions in an if, similar to alex's solution:
def form_valid(self, form):
if not self.request.is_ajax()
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)
Upvotes: 1