我有这个错误cart/create/?product_id=1 500 (Internal Server Error)我不明白为什么:)我正在尝试首先使用Ajax。尝试在购物车中添加产品,但不刷新页面。
从此链接添加产品
<a href="#" data-id="{{ product.id }}" class="add_to_cart"><button>Add product</button></a>我的url
url(r'^cart/create/$', views.cart_create, name='cart_create'),我的观点
def cart_create(request):
cart = Cart(request)
product_id = request.GET.get('product_id')
product = Product.objects.get(id=product_id)
cart.add(product=product)
return JsonResponse('')js
<script type="text/javascript">
$(document).ready(function(){
$('.add_to_cart').on('click', function(){
product_id = $(this).attr('data-id')
data = {
product_id: product_id
}
$.ajax({
type: 'GET',
url: '{% url "cart:cart_create" %}',
data: data,
success: function(data){
console.log('success')
}
})
})
});
</script>这个base.html文件,在这里我尝试在购物车中输出我的计数,这是有效的,但只在刷新时有效
<header>
{% with total_items=cart|length %}
{% if cart|length > 0 %}
Our cart:
<a href="{% url 'cart:cart_show' %}" id="cart_count">
{{ total_items }} products {{ cart.get_total_price }} ₽
</a>
{% else %}
<a href="{% url 'cart:cart_show' %}">Cart is empty</a>
{% endif %}
{% endwith %}
<h1><a href="{% url 'shop:product_list' %}">Main</a ></h1>
</header>为什么我做错了呢?
terminal
Internal Server Error: /cart/create/
Traceback (most recent call last):
File "/home/kory/project/django-shop/.env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/kory/project/django-shop/.env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kory/project/django-shop/.env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kory/project/django-shop/cart/views.py", line 21, in cart_create
return JsonResponse('')
File "/home/kory/project/django-shop/.env/lib/python3.7/site-packages/django/http/response.py", line 552, in __init__
'In order to allow non-dict objects to be serialized set the '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.console.log
jquery.min.js:4 GET http://localhost:8000/cart/create/?product_id=1 500 (Internal Server Error)发布于 2019-05-06 21:31:41
有关JsonResponse的说明,请参阅docs。
您需要向JsonResponse传递一个dict,而不仅仅是一个空字符串。或者,如果设置为safe=False,则可以传递一个json可序列化对象。但即便如此,我也不认为空字符串是有效的JSON。
https://stackoverflow.com/questions/56005983
复制相似问题