如何将html中的javascript变量传递给views.py?



我目前正在尝试使用django做一个网站。我遇到了一个问题,就像我在标题中写的。

我想做的是这样的,

首先,商店页面展示了所有产品。但是,当用户在下拉菜单中选择一个品牌名称时,商店页面必须只显示该品牌的产品。

要做到这一点,我必须得到一个变量,用户选择下拉菜单,我的视图函数应该同时运行

请告诉我如何解决这个问题。

我在HTML中做了一个下拉菜单,如下图所示。


<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>

和my views.py如下。



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)

我试着谷歌它很多次,但我无法解决这个

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)

从技术上讲,我们没有传递一个JS变量。我们只是从请求对象中检索一个变量。

事实上,如果我们使用JS使用AJAX发送值,主要的区别将是页面不被重新加载。

最新更新