Django项目实战 - 分类筛选功能


第一步: 在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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM