Django Ajax form not being saved

后端 未结 1 1224
孤街浪徒
孤街浪徒 2021-01-26 12:51

I want to use Ajax in Django to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to :

return HttpResp

相关标签:
1条回答
  • 2021-01-26 13:23

    I would personally split these up in two views, because they do different stuff.

    But, if you want to keep it that way, you can do the following:

    First of all, because you are making an AJAX Request, you should return a JsonResponse object.

    In your view you can render the checkout.html and pass it as a context variable to your json response:

    def add_user_address(request):
       ...
    
       data = dict()
       context = {
           'address_form': form,
           ...
       }
    
       data['html_form'] = render_to_string("checkout.html",
                                            context,
                                            request=request)
       return JsonResponse(data)
    

    And in your $.ajax success function you can do the following

    success: function(data) {
      // console.log(data);
      $("div-to-replace-html").html(data.html_form);
    
    }
    
    0 讨论(0)
提交回复
热议问题