尝试添加到没有刷新页面Django / Ajax的购物车中(内部服务器错误)

时间:2019-05-06 13:11:29

标签: ajax django forms

我遇到此错误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(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 }} &#8381;
            </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)

1 个答案:

答案 0 :(得分:1)

有关JsonResponse的说明,请参见docs

您需要将dict传递给JsonResponse,而不仅仅是空字符串。或者,如果您设置safe=False,则可以传递json可序列化对象。但是即使那样,我也不认为空字符串是有效的JSON。