scoder
scoder

Reputation: 11

Why is form_valid() being executed twice?

I am trying to show a Bootstrap Form Modal instead of the usual form in Django. I have written the following code. However, the form_valid() method executes twice when the modal is submitted, thus adding the data twice in the database. Any help would be appreciated.

    form_class = CreateTransacionForm
    template_name = 'create.html'
    success_url = '/main/'
    success_message = 'Transaction created'

    def form_valid(self, form):
        obj = form.save(commit=False)
        ## Do some additional tasks
        obj.save()
        return HttpResponseRedirect(reverse('main'))

The request looks like this

Upvotes: 0

Views: 278

Answers (1)

KiloByte
KiloByte

Reputation: 21

Insert:

if not self.request.is_ajax():

def form_valid(self, form):
    if not self.request.is_ajax():
        obj = form.save(commit=False)
        ## Do some additional tasks
        obj.save()
    return HttpResponseRedirect(reverse('main'))

Upvotes: 2

Related Questions