How to pass a javascript variable in html to views.py?

Question:

I am currently trying to make an website using django.
And i faced a problem like i wrote in title.

What i want to make is like this,

first of all, shop page shows all products.
But, when a user select a brand name on dropdown menu, shop page must shows only that brand products.

To do this, i have to get a variable which a user select on dropdown menu,
and my view function should run at the same time.

Please let me know how can i resolve this.

i made a dropdown in html as below.


<shop_test.html>

<form action="{% url 'shop' %}" method="get" id="selected_brand">
<select name="selected_brand" id="selected_brand">
    <option value="ALL">Select Brand</option>
    <option value="A">A_BRAND</option> 
    <option value="B">B_BRAND</option>
    <option value="C">C_BRAND</option>
</select>
</form>

<script type="text/javascript">
    $(document).ready(function(){
        $("select[name=selected_brand]").change(function () {
        $(".forms").submit();

        });
    });
</script>

and my views.py is as below.



def ShopView(request):
    brand_text = request.GET.get('selected_brand')

    if brand_text == None:
        product_list = Product.objects.all()
    elif brand_text != 'ALL':
        product_list = Product.objects.filter(brand=brand_text)
    else:
        product_list = Product.objects.all()

    context = {
                'brand_text': brand_text,
                'product_list': product_list,
            }
    return render(request, 'shop_test.html', context)

i tried to google it a lot of times, but i counldn’t resolve this.

Asked By: Mircea Im

||

Answers:

base.html

{% load static %}

<!DOCTYPE html>
<html lang='en'>
    <head>
        <title>{% block title %}My amazing site{% endblock %}</title>
        <meta charset='utf-8'>
        <link rel="stylesheet" href="{% static 'base.css' %}">
    </head>

    <body>
        <div id="content">
            {% block content %}{% endblock %}
        </div>
    </body>

    <footer>
        {% block script %}{% endblock %}
    </footer>
</html>

blank.html

{% extends 'base.html' %}

{% block content %}
    <form action="{% url 'core:pass-variable-js' %}" method="get" onChange=sendForm() id="selection_form">
        <select name="selected_brand" id="selected_brand">
            <option value="ALL" {% if brand == "ALL" %}selected{% endif %}>Select Brand</option>
            <option value="A" {% if brand == "A" %}selected{% endif %}>A_BRAND</option> 
            <option value="B" {% if brand == "B" %}selected{% endif %}>B_BRAND</option>
            <option value="C" {% if brand == "C" %}selected{% endif %}>C_BRAND</option>
        </select>   
    </form>

    {% for product in products%}
    <div>
        <p>Product: {{ product.name }}<br>Brand: {{ product.brand }}</p><br>
    </div>
    {% endfor %}
{% endblock %}

{% block script %}
    <script>
        function sendForm() {
            document.getElementById("selection_form").submit();
        }
    </script>
{% endblock %}

views.py

def pass_js_variable(request):
    brand = 'ALL'
    products = Product.objects.all()

    if request.GET.get('selected_brand'):
        brand = request.GET.get('selected_brand')
        match brand:
            case 'ALL':
                products = Product.objects.all()
            case default:
                products = Product.objects.filter(brand=brand)

    context = {'brand': brand, 'products': products}
    return render(request, 'blank.html', context)

Technically we are not passing a JS variable. We are just retrieving an variable from the request object.

In fact, if we use JS to send the value using AJAX the main difference would be the page NOT being reloaded.

Answered By: Niko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.