Код: Выделить всё
response = JsonResponse(data={'Product Name: ': str(product.name)}, status=201)
вот файл URL-адресов
Код: Выделить всё
from django.urls import path
from . import views
urlpatterns = [
path('', views.cart_summary, name="cart_summary"),
path('add', views.cart_add, name="cart_add"),
path('delete/', views.cart_delete, name="cart_delete"),
path('update/', views.cart_update, name="cart_update"),
]
Код: Выделить всё
def cart_add(request):
# Get the cart
cart = Cart(request)
# test for POST
if request.POST.get('action') == 'post':
# Get stuff
product_id = int(request.POST.get('product_id'))
# lookup product in DB
product = get_object_or_404(Product, id=product_id)
print(product.name)
# Save to session
cart.add(product=product)
print("Successfully returned from cart object add function... added new product to cart")
# Return Response
response = JsonResponse(data={'Product Name: ': str(product.name)}, status=201)
return response
Код: Выделить всё
class Cart():
def __init__(self, request):
self.session = request.session
# Get the current session key if it exists
cart = self.session.get('session_key')
# If the user is new, no session key! Create one!
if 'session_key' not in request.session:
cart = self.session['session_key'] = {}
# Make sure cart is available on all pages of site
self.cart = cart
def add(self, product):
product_id = str(product.id)
if product_id in self.cart:
pass
else:
print("In cart object add function product id:" + product_id)
print("Same place product price: " + str(product.price))
self.cart[product_id] = {'price', str(product.price)}
print("Trying to set session modification token to true")
self.session.modified = True
Код: Выделить всё
{% extends 'base.html' %}
{% load static %}
{% block content %}
[img]{{product.image.url}}[/img]
{{ product.name }}
{{ product.description }}
{% if product.is_sale %}
Sale
${{product.price}}
${{product.sale_price}}
ID: {{product.id}}
{% else %}
${{product.price}}
{% endif %}
[url={% url ]
Home
[/url]
Add to Cart
// Check if Button pressed
$(document).on('click', '#add-cart', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'cart_add' %}',
data: {
product_id: $('#add-cart').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
action: 'post'
},
success: function(json){
console.log(json)
},
error: function(xhr, errmsg, err) {
}
});
})
{% endblock %}
Код: Выделить всё
Код: Выделить всё
$.ajax({
type: 'POST',
url: '/cart/add',
data: {
product_id: $('#add-cart').val(),
csrfmiddlewaretoken: 'uSwH0Uyb5rrOXmDHWnd0DjpRmHfWUqsyD0aqU3YqdlV5EnFA9NvvdDRyBcHMq7SZ',
action: 'post'
},
Вот полный журнал ошибок, как просили в комментариях:
Код: Выделить всё
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1073, in _bootstrap_inner
self.run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1010, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
self.check(display_num_errors=True)
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\management\base.py", line 486, in check
all_issues = checks.run_checks(
^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces
url_patterns = getattr(resolver, "url_patterns", [])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\utils\functional.py", line 47, in __get__
res = instance.__dict__[self.name] = self.func(instance)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\urls\resolvers.py", line 738, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\utils\functional.py", line 47, in __get__
res = instance.__dict__[self.name] = self.func(instance)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\urls\resolvers.py", line 731, in urlconf_module
return import_module(self.urlconf_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 90, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 1387, in _gcd_import
File "", line 1360, in _find_and_load
File "", line 1331, in _find_and_load_unlocked
File "", line 935, in _load_unlocked
File "", line 995, in exec_module
File "", line 488, in _call_with_frames_removed
File "C:\Users\macai\PythonProjects\ecom\ecom\ecom\urls.py", line 9, in
path('cart/', include ("cart.urls")),
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\urls\conf.py", line 39, in include
urlconf_module = import_module(urlconf_module)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 90, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 1387, in _gcd_import
File "", line 1360, in _find_and_load
File "", line 1331, in _find_and_load_unlocked
File "", line 935, in _load_unlocked
File "", line 995, in exec_module
File "", line 488, in _call_with_frames_removed
File "C:\Users\macai\PythonProjects\ecom\ecom\cart\urls.py", line 2, in
from . import views
File "C:\Users\macai\PythonProjects\ecom\ecom\cart\views.py", line 26
response = JsonResponse(data
=['Product Name: ': str(product.name)], status=201)
Подробнее здесь: https://stackoverflow.com/questions/787 ... uery-error