我创建了三个选项(主页,更改密码和注销)的菜单。在家中,我显示了存储在数据库中的所有书籍。现在我想使用复选框根据书籍的类别过滤内容。默认情况下,所有图书都会在过滤分类时显示,但只显示该分类的图书。但对于我来说,即使点击所有复选框(复选框包含分类),它也会显示所有图书。我认为存在一些问题在我的模板文件中。如何从django模板中定义的复选框检索值
urls.py,
url(r'^welcome_user/$',views.welcome_user, name='welcome_user'),
Models.py,
class Add_cat(models.Model):
category = models.CharField("Name",max_length=25,unique=True)
def __unicode__(self):
return u'{0}'.format(self.category)
class Add_prod(models.Model):
book = models.CharField("Book Name",max_length=40)
author = models.CharField("Author",max_length=30)
price = models.PositiveIntegerField("Price")
image = models.ImageField(upload_to='images',null=True)
cat = models.ForeignKey(Add_cat,on_delete=models.CASCADE)
模板文件,
{% block content %}
{% load staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
<div class="box">
<div class="sideNav">
<form action="{% url 'welcome_user' %}">
<p id=id3>Categories</p>
<hr>
{% for i in products %}
<input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}<br>
{% endfor %}
<button type="submit">Submit</button>
</form>
</div>
<div>
{% for i in products %}
<div style="display:inline-block;margin:30px">
<img src="{{i.image.url}}" alt="No Image" width=196px height=196px>
<p id=id4>Rs.{{i.price}}</p>
</div>
{% endfor %}
</div>
</div>
</body>
{% endblock %}
Views.py,
@login_required
def welcome_user(request):
if 'cat_name' in request.GET:
filter_category = request.GET.getlist('cat_name')
my_products = Add_prod.objects.filter(cat__in=filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
嘿模板只在点击主菜单时才会调用。当我点击任何类别的模板时不会被调用 – Bhanukiran
如何做滤波器呢?你使用任何js函数吗?你必须为做这个过滤器做一些操作。您可以使用基于复选框选择的js代码执行此过滤器,或者您必须调用后端服务以获取过滤响应。 – Anoop