第一步: 在HTML頁面中獲取city.id
{% for city in all_citys %} <a href="?city={{ city.id }}"><span class="">{{ city.name }}</span></a> {% endfor %}
第二步: 在views.py中獲取html中的city.id 來進行判斷,
1. 通過html中的city字段,獲取city.id
2. 然后根據city.id進行filter(因為CourseOrg有一個外鍵指向citydict)
city_id = request.GET.get("city", "") if city_id: all_orgs = all_orgs.filter(city_id=int(city_id))
第三步: 在HTML中配置選中激活顯示(加亮顯示)
<a href="?ct="><span class="{% ifequal city_id "" %}active2{% endifequal %}">全部</span></a>
<a href="?city={{ city.id }}"><span class="{% ifequal city_id city.id|stringformat:"i" %}active2{% endifequal %}">{{ city.name }}</span></a>
views.py代碼
class OrgView(View): """ 課程機構列表功能 """ def get(self, request): # 課程機構 all_orgs = CourseOrg.objects.all()# 城市 all_citys = CityDict.objects.all() # 取出篩選城市 city_id = request.GET.get("city", "") if city_id: all_orgs = all_orgs.filter(city_id=int(city_id)) # 對課程機構進行分頁 try: page = request.GET.get("page", 1) except PageNotAnInteger: page = 1 p = Paginator(all_orgs, 3, request=request) orgs = p.page(page) org_nums = all_orgs.count() return render(request, "org-list.html", { "all_orgs": orgs, "all_citys": all_citys, "org_nums": org_nums })
HTML代碼
<div class="cont"> <a href="?ct="><span class="{% ifequal city_id "" %}active2{% endifequal %}">全部</span></a> {% for city in all_citys %} <a href="?city={{ city.id }}"><span class="{% ifequal city_id city.id|stringformat:"i" %}active2{% endifequal %}">{{ city.name }}</span></a> {% endfor %} </div>