Home > Enterprise >  Use JS onclick to pass some data to Django views.py?
Use JS onclick to pass some data to Django views.py?

Time:09-22

I want send product id to my views.

Templates

<div class="products__header--search-result">
    <ul>
        {% for product in products %}
            <li onclick="change('{{ product.id }}')"><a href="#">{{ product.name }}</a></li>
        {% endfor %}
    </ul>
</div>

<script>
    function change(foo) {
        $.ajax({
            url: {% url 'dashboard' %},
            data: {
                'foo': foo,
            },
        });
    }
</script>

views.py

myRequets = request.GET.get('foo')

But myRequets return 'None'

How can I fix this? Is there a better way to pass values to views.py?

CodePudding user response:

You don't need JS to do this because Django allows parameters in urls:

# URLconf
from django.urls import path

from . import views

urlpatterns = [
    path('product/', views.product),
    path('product/<int:product_id>/', views.product),
]

views.py

# View (in product/views.py)
def product(request, product_id=None):
    products = None
    if product_id:
       # Output the appropriate page of product entry, according to product_id.
        return ...
    # Output the appropriate page when product_id is None
    return ...

Source: https://docs.djangoproject.com/en/3.2/topics/http/urls/#example (adapted)

Then in your template:

{% if products %}
<div class="products__header--search-result">
    <ul>
        {% for product in products %}
            <li><a href="/product/{{ product_id }}/">{{ product.name }}</a></li>
        {% endfor %}
    </ul>
</div>
{% endif %}
  • Related