为什么form_valid()被执行两次?

时间:2019-05-11 18:06:58

标签: django django-forms

我试图显示一个Bootstrap Form Modal,而不是Django中的通常形式。我写了下面的代码。但是,提交模态后,form_valid()方法执行两次,从而将数据两次添加到数据库中。任何帮助将不胜感激。

    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'))

请求看起来像this

1 个答案:

答案 0 :(得分:1)

插入:

如果不是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'))