-1

So I'll preface this question by stating I think the error could be in a few places though the most likely, especially according to the windows command prompt is SyntaxError: Invalid syntax on this line

response = JsonResponse(data={'Product Name: ': str(product.name)}, status=201)

full code in context of the file down below. Though there maybe another culprit causing the the code to go awry. I suspect my javascript and jquery is so weak that I can't notice I'm not grabbing the identifier of the DOM element like I think I'm doing in jquery

here's the urls file

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"),
]

here's the view in question

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

Here's the cart object and add function including the init for the cart object

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

Lastly here's my template

{% extends 'base.html' %}
{% load static %}
{% block content %}

<div class="container">
    <br/><br/>
    <div class="card mb-8" style="max-width: 720px;">
        <div class="row g-0">
            <div class="col-md-4">
                <img src="{{product.image.url}}" class="img-fluid rounded-start" alt="...">
            </div>
            <div class="col-md-8">
                  <div class="card-body">
                      <center>
                        <h5 class="card-title">{{ product.name }}</h5>
                        <p class="card-text">{{ product.description }}</p>
                          {% if product.is_sale %}
                            <!-- Sale -->
                                <div class="d-flex justify-content-center small text-warning mb-2">
                                    <div class="bi-star-fill"></div>
                                    <span class="text-dark">&nbsp;&nbsp;Sale&nbsp;&nbsp;</span>
                                    <div class="bi-star-fill"></div>
                                </div>

                                <!-- Product price-->
                                <strike>${{product.price}}</strike>
                                &nbsp;${{product.sale_price}}
                                    <br/> ID: {{product.id}}
                          {% else %}
                            ${{product.price}}
                          {% endif %}
                            <br/><br/>
                          <a href="{% url 'home' %}" class="btn btn-secondary">
                              Home
                          </a>
                          <button type=button value="{{ product.id}}" class="btn btn-secondary" id="add-cart">Add to Cart</button>
                      </center>
                  </div>
            </div>
        </div>
    </div>

    <br/><br/>
    <br/><br/>
    <br/><br/>
    <br/><br/>
</div>
<script>
// 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) {

            }
    });
    })


</script>
{% endblock %}

there's a script in base.html to include jquery, here's a snippet of that code

<script
      src="https://code.jquery.com/jquery-3.7.1.min.js"
      integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
      crossorigin="anonymous"></script>

When I inspect the ajax after clicking on the button here's what I see

$.ajax({
    type: 'POST',
    url: '/cart/add',
    data: {
        product_id: $('#add-cart').val(),
        csrfmiddlewaretoken: 'uSwH0Uyb5rrOXmDHWnd0DjpRmHfWUqsyD0aqU3YqdlV5EnFA9NvvdDRyBcHMq7SZ',
        action: 'post'
    },

to my amatuer eyes product_id should read an integer of what the product ID is, so I don't know if all this is an error where jquery isn't interperting like I expect.

Here's the full tracebook of the error as requested in the comments:

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 "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "C:\Users\macai\PythonProjects\ecom\ecom\ecom\urls.py", line 9, in <module>
    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 "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "C:\Users\macai\PythonProjects\ecom\ecom\cart\urls.py", line 2, in <module>
    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)

after updating python the firist traceback was replaced with the following

  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\utils\deprecation.py", line 136, in __call__
    response = self.process_response(request, response)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\contrib\sessions\middleware.py", line 59, in process_response
    request.session.save()
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\contrib\sessions\backends\db.py", line 82, in save
    obj = self.create_model_instance(data)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\contrib\sessions\backends\db.py", line 69, in create_model_instance
    session_data=self.encode(data),
                 ^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\contrib\sessions\backends\base.py", line 94, in encode
    return signing.dumps(
           ^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\signing.py", line 152, in dumps
    return TimestampSigner(key=key, salt=salt).sign_object(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\signing.py", line 250, in sign_object
    data = serializer().dumps(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\macai\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\django\core\signing.py", line 127, in dumps
    return json.dumps(obj, separators=(",", ":")).encode("latin-1")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
          ^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable

for the other comment: I get a error 500 internal server error with the name of add type Post

4
  • Go use your browser developer tools, network panel, to inspect what response this request actually got.
    – CBroe
    Commented Jul 8 at 13:28
  • 1
    Please, edit the question and share the full traceback as code (not an image). Normally the Django error page has a function to turn the error in a text format that includes settings, traceback, etc. Commented Jul 8 at 13:56
  • @cbroe Should I include request and response headers what i see in network is, I get a error 500 internal server error with the name of add type Post Commented Jul 8 at 15:12
  • did I forget to include anything? I got -1, which I can kinda agree with, and no indication on where to go with my program Commented Jul 10 at 16:44

0

Browse other questions tagged or ask your own question.