Django Ajax form not being saved

孤街浪徒 提交于 2020-04-27 05:33:39

问题


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 HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True

But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on

As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django.

What I want to do is that after they submit the place order button, the form is going to be None, i.e disappear and then I would add a credit card form there for payment. But it is not happening. What is wrong here? How can I do this or is there a better way to do this?

My forms.py:

class UserAddressForm(forms.ModelForm):
    class Meta:
        model = UserAddress
        fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"]

My accounts.views.py:

def add_user_address(request):
    try:
        next_page = request.GET.get("next")
    except:
        next_page = None
    if request.method == "POST":
        form = UserAddressForm(request.POST)
        if form.is_valid():
            new_address = form.save(commit=False)
            new_address.user = request.user
            new_address.save()
            if next_page is not None:
                return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True")
    else:
        raise Http404

My orders.views.py:

@login_required()
def checkout(request):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        the_id = None
        return redirect(reverse("myshop-home"))

    try:
        new_order = Order.objects.get(cart=cart)
    except Order.DoesNotExist:
        new_order = Order(cart=cart)
        new_order.cart = cart
        new_order.user = request.user
        new_order.order_id = id_generator()
        new_order.save()
    except:
        return redirect(reverse("cart"))


    try:
        address_added = request.GET.get("address_added")
    except:
        address_added = None 

    if address_added is None:
        address_form = UserAddressForm()
    else:
        address_form = None

    if new_order.status == "Finished":
        #cart.delete()
        del request.session['cart_id']
        del request.session['items_total']
        return redirect(reverse("cart"))


    context = {"address_form": address_form, "cart": cart}
    template = "orders/checkout.html"
    return render(request, template, context)

My urls.py:

path('ajax/add_user_address', accounts_views.add_user_address, name='ajax_add_user_address'),

My checkout.html:

<form method="POST" action="{% url 'ajax_add_user_address' %}?redirect=checkout">
    {% csrf_token %}
    <fieldset class="form-group">   
        {{ address_form|crispy }}
    </fieldset>
    <div class="form-group">
        <button class="btn btn-outline-dark" type="submit">Place Order</button>
    </div>
</form>

回答1:


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

}


来源:https://stackoverflow.com/questions/61286082/django-ajax-form-not-being-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!