複選框有兩種狀態(選中和未選中)。在我看來,我有幾種產品,我試圖根據它的類別進行過濾。當我點擊任何複選框時,複選框狀態正在改變(取消選中)。我也是無法選擇多個複選框。如何在django提交後保留複選框狀態?
Models.py,
class Add_cat(models.Model):
category = models.CharField("Name")
cat_name = models.BooleanField(default=False)
我的模板文件,
<head>
<script type="text/javascript">
function myfunction(){
document.getElementById("myform").submit();
}
</script>
</head>
<body>
<form action="{% url 'welcome_user' %}" id="myform">
{% csrf_token %}
<p >Categories</p>
{% for i in My_Cat %}
<input type="checkbox" name="cat_name" value="{{i.category}}"
onclick="return myfunction()"
{% if add_cat.cat_name %}checked="checked"{% endif %}>{{i.category}}
{% endfor %}
</form>
</body>
Views.py,
#Add_prod class contains product list with category as foreign key to Add_cat
def welcome_user(request):
categories = Add_cat.objects.all()
if 'cat_name' in request.GET:
filter_category = request.GET.getlist('cat_name')
my_products = Add_prod.objects.filter(cat__category__in = filter_category)
context = {
"My_Cat":categories,
"products":my_products
}
if 'cat_name' not in request.GET:
my_products = Add_prod.objects.all()
context = {
"My_Cat":categories,
"products":my_products
}
return render(request,"welcome-user.html",context)
'add_cat'應該是什麼? – Sayse
它的數據庫名稱 – Bhanukiran