Django模版语言自定义标签-实现前端 关联组合过滤查询

前端关联 组合过滤查询

实现效果如图:

models.py 创建表代码

from django.db import models

# Create your models here.

class Level(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name

# 方向
class Direction(models.Model):
    name = models.CharField(max_length=32)
    d_2_c = models.ManyToManyField('Category')

    def __str__(self):
        return self.name

# 类型
class Category(models.Model):
    name = models.CharField(max_length=32)
    def __str__(self):
        return self.name

# #反向
# models.Category.objects.filter(Direction__id =id)
# # 正向
# models.Direction.objects.filter(id = id).d_2_c.all()

class Video(models.Model):
    lv = models.ForeignKey(Level)
    cg = models.ForeignKey(Category)

    title = models.CharField(verbose_name='标题', max_length=32)
    summary = models.CharField(verbose_name='简介', max_length=32)
    img = models.ImageField(verbose_name='图片', upload_to='./static/images/Video/')
    href = models.CharField(verbose_name='视频地址', max_length=256)

    create_date = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.title

urls.py路由分发代码

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^video-(?P<dr_id>\d+)-(?P<cg_id>\d+)-(?P<lv_id>\d+).html',views.video,name='vvv2'),
]

views.py视图函数代码

from django.shortcuts import render
from app01 import models

# Create your views here.
def video(request,*args,**kwargs):
    # 0-0-0.html
    # 0-1-0.html
    # 1-0-0.html
    # 1-1-0.html [1,2,3,4]
    # 2-1-0.html [2,3,4]
    dr_id = kwargs.get('dr_id')
    cg_id = kwargs.get('cg_id')
    lv_id = kwargs.get('lv_id')
    condition = {}

    drection_list = models.Direction.objects.all()
    level_list = models.Level.objects.all()

    if dr_id == "0":
        # 未选择方向
        category_list = models.Category.objects.all()
        if cg_id == '0':
            # 未选择分类
            pass
        else:
            # 选择分类
            # models.Video.objects.filter(cg_id=cg_id)
            condition['cg_id'] = cg_id
    else:
        # 选择了方向
        category_list = models.Category.objects.filter(direction=dr_id)

        temp = category_list.values_list('id')
        cg_id_list = list(zip(*temp))[0]

        if cg_id == '0':
            # 未选择分类
            condition['cg_id__in'] = cg_id_list
        else:
            # 选择了分类
            if int(cg_id) in cg_id_list:
                condition['cg_id'] = cg_id
            else:
                condition['cg_id__in'] = cg_id_list
                kwargs['cg_id'] = '0'

    if lv_id == '0':
        pass
    else:
        condition['lv_id'] = lv_id

    result = models.Video.objects.filter(**condition)
    print(result)

    return render(request, 'video.html', {
        'drection_list': drection_list,
        'level_list': level_list,
        'category_list': category_list,
        'arg_dict': kwargs,
        'result':result,
    })

自定义标签 templatetags xx.py代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017/2/6
# @Author  : Jesson 
# @Blog    : http://www.cnblogs.com/hellojesson/
#
from django import template
from django.utils.safestring import mark_safe
register = template.Library()

# 方向
@register.simple_tag
def dr_tag(obj,arg_dict):
    """
    生成A标签
    :param obj:
    :param arg_dict:
    :return:
    """
    from django.urls import reverse

    url = reverse('vvv2', kwargs={'dr_id': obj.id, 'cg_id': arg_dict.get('cg_id'), 'lv_id': arg_dict.get('lv_id')})

    if str(obj.id) == arg_dict.get('dr_id'):
        # 获取当前URL
        tag = "%s" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "%s" % (url, obj.name)
        return mark_safe(tag)

# 类别
@register.simple_tag
def cg_tag(obj,arg_dict):
    from django.urls import reverse

    url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': obj.id, 'lv_id': arg_dict.get('lv_id')})

    if str(obj.id) == arg_dict.get('cg_id'):
        # 获取当前URL
        tag = "%s" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "%s" % (url, obj.name)
        return mark_safe(tag)

# 难度级别
@register.simple_tag
def lv_tag(obj,arg_dict):
    from django.urls import reverse

    url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': arg_dict.get('cg_id'), 'lv_id': obj.id})

    if str(obj.id) == arg_dict.get('lv_id'):
        # 获取当前URL
        tag = "%s" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "%s" % (url, obj.name)
        return mark_safe(tag)

# 全部显示
@register.simple_tag
def total_tag_2(arg_dict,key):
    from django.urls import reverse
    if key == 'dr_id':
        url = reverse('vvv2', kwargs={'dr_id': 0, 'cg_id': arg_dict.get('cg_id'), 'lv_id': arg_dict.get('lv_id')})
    elif key == 'cg_id':
        url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': 0, 'lv_id': arg_dict.get('lv_id')})

    elif key == 'lv_id':
        url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': arg_dict.get('cg_id'), 'lv_id': 0})
    else:
        url = ''
    if arg_dict.get(key) == '0':
        tag = "全部" % (url,)
    else:
        tag = "全部" % (url,)
    return mark_safe(tag)

前端video.html 代码

{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .filter {
            background-color: #EFEFEF;
            line-height: 20px;
            margin-top: 20px;
        }
        .filter a{
            display: inline-block;
            text-decoration:none;
            margin: 5px;
            padding: 3px 5px;
        }
        .filter a.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <h2>筛选条件</h2>
    <div class="filter">
        <div>
            <a>方向:</a>
            {% total_tag_2 arg_dict 'dr_id' %}
            {% for item in drection_list %}
                <!-- if判断,如果kwargs.dr_id = item.id
                    - 加入样式
                else:
                    - 无样式
                   -->
                {% dr_tag item arg_dict %}
            {% endfor %}

        </div>
        <div>
            <a>分类:</a>
            {% total_tag_2 arg_dict 'cg_id' %}
            {% for item in category_list %}
                {% cg_tag item arg_dict %}
            {% endfor %}
        </div>
        <div>
            <a>难度:</a>
            {% total_tag_2 arg_dict 'lv_id' %}
            {% for item in level_list %}
                {% lv_tag item arg_dict %}
            {% endfor %}
        </div>
    </div>

    <h2>查询结果</h2>
    <div class="content">
        {% for row in result %}
            <div style="width: 100px;height: 260px;float: left;margin: 3px;">
                <img style="width: 100px;height: 150px;" src="{{ row.img }}">
                <p>{{ row.title }}</p>
                <p>{{ row.summary }}</p>
            </div>
        {% endfor %}
    </div>
</body>
</html>
posted @ 2017-02-07 11:33  hello-Jesson  阅读(570)  评论(0编辑  收藏  举报