Django Ajax表单未保存 [英] Django Ajax form not being saved
问题描述
我要在Django中使用Ajax来处理我的结帐表单提交后的视图.提交表单后,我希望它转到:
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")
,即 http://127.0.0.1:8000/checkout/? address_added = True
但是由于某种原因,它没有去那里.而是要转到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
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
结果,表单数据也没有被保存.我在想这是否是因为新版本的Django.
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?
我的forms.py:
My forms.py:
class UserAddressForm(forms.ModelForm):
class Meta:
model = UserAddress
fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"]
我的accounts.views.py:
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
我的orders.views.py:
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)
我的urls.py:
path('ajax/add_user_address', accounts_views.add_user_address, name='ajax_add_user_address'),
我的checkout.html:
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>
推荐答案
我个人将它们分成两个视图,因为它们做的是不同的事情.
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:
首先,因为您正在发出AJAX请求,所以您应该返回JsonResponse对象.
First of all, because you are making an AJAX Request, you should return a JsonResponse object.
在您看来,您可以呈现checkout.html并将其作为上下文变量传递给json响应:
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)
在您的$.ajax
成功功能中,您可以执行以下操作
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);
}
这篇关于Django Ajax表单未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!