Django模板语言之组合搜索

 

url.py

 1 from django.conf.urls import url
 2 from django.contrib import admin
 3 from app01 import views
 4 urlpatterns = [
 5     # url(r'^admin/', admin.site.urls),
 6     # url(r'^index/', views.index),
 7     # url(r'^student/', views.student),
 8     # url(r'^student1.html', views.student1),
#direction_id,classification_id,level_id作为参数传递给def video(request, *arg, **kwargs):
9 url(r'^video-(?P<direction_id>\d+)-(?P<classification_id>\d+)-(?P<level_id>\d+).html', views.video), 10 ]
 1 from django.db import models
 2 
 3 class Direction(models.Model):
 4     weight = models.IntegerField(verbose_name='权重(按从大到小排列)', default=0)
 5     name = models.CharField(verbose_name='名称', max_length=32)
 6 
 7     classification = models.ManyToManyField('Classification')
 8 
 9     class Meta:
10         db_table = 'Direction'
11         verbose_name_plural = u'方向(视频方向)'
12 
13     def __str__(self):
14         return self.name
15 
16 
17 class Classification(models.Model):
18     weight = models.IntegerField(verbose_name='权重(按从大到小排列)', default=0)
19     name = models.CharField(verbose_name='名称', max_length=32)
20 
21     class Meta:
22         db_table = 'Classification'
23         verbose_name_plural = u'分类(视频分类)'
24 
25     def __str__(self):
26         return self.name
27 
28 
29 class Video(models.Model):
30 
31     status_choice = (
32         (0, u'下线'),
33         (1, u'上线'),
34     )
35     level_choice = (
36         (1, u'初级'),
37         (2, u'中级'),
38         (3, u'高级'),
39     )
40     status = models.IntegerField(verbose_name='状态', choices=status_choice, default=1)
41     level = models.IntegerField(verbose_name='级别', choices=level_choice, default=1)
42     classification = models.ForeignKey('Classification', null=True, blank=True)
43 
44     weight = models.IntegerField(verbose_name='权重(按从大到小排列)', default=0)
45 
46     title = models.CharField(verbose_name='标题', max_length=32)
47     summary = models.CharField(verbose_name='简介', max_length=32)
48     img = models.ImageField(verbose_name='图片', upload_to='./static/images/Video/')
49     href = models.CharField(verbose_name='视频地址', max_length=256)
50 
51     create_date = models.DateTimeField(auto_now_add=True)
52 
53     class Meta:
54         db_table = 'Video'
55         verbose_name_plural = u'视频'
56 
57     def __str__(self):
58         return self.title
modles.py
 1 import json
 2 from django.shortcuts import render,HttpResponse
 3 from app01 import models
 4 def video(request,*args,**kwargs):
 5     print("www",kwargs)#**kwargs为字典:{'direction_id': '0', 'classification_id': '0', 'level_id': '0'}
 6     print(request.path)
 7     # 获取当前url:/video-0-0-0.html
 8     request_path = request.path#获取当前url:/video-0-0-0.html
 9 
10 
11     q = {}
12     q['status'] = 1
13 
14     class_id = int(kwargs.get('classification_id'))#获取视频分类__方向id
15 
16     direction_list = models.Direction.objects.all().values('id','name')#获取所有方向表的id和name
17 
18     if kwargs.get('direction_id') == '0':#如果方向__视频分类id等于0
19         # 方向选择全部
20         print('方向等于0')
21         class_list = models.Classification.objects.all().values('id', 'name')#获取所有视频分类的id和name
22         if kwargs.get('classification_id') == '0':#如果视频分类__方向id等于0
23             pass
24         else:
25             # 当前分类是 1
26             q['classification_id__in'] = [class_id,]
27 
28     else:
29         print('方向不为0')
30         # 方向选择某一个方向,
31         # 如果分类是0
32         if kwargs.get('classification_id') == '0':
33             print('分类为0')
34             obj = models.Direction.objects.get(id=int(kwargs.get('direction_id')))#获取当前方向id
35             class_list = obj.classification.all().values('id', 'name')#获取当前方向的视频分类id和name
36             print(class_list)
37             id_list = list(map(lambda x: x['id'], class_list))#获取x['id']的值
38             print(id_list)
39             q['classification_id__in'] = id_list
40         else:
41 
42             obj = models.Direction.objects.get(id=int(kwargs.get('direction_id')))
43             class_list = obj.classification.all().values('id', 'name')
44             id_list = list(map(lambda x:x['id'], class_list))
45             q['classification_id__in'] = [class_id,]
46             print('分类不为0')
47             # 当前分类如果在获取的所有分类中,则方向下的所有相关分类显示
48             # 当前分类如果不在获取的所有分类中,
49             # if kwargs.get('classification_id') in
50             if int(kwargs.get('classification_id')) in id_list:
51                 pass
52             else:
53                 print('不再,获取指定方向下的所有分类:选中的回到全部')
54                 url_part_list = request_path.split('-')
55                 url_part_list[2] = '0'
56                 request_path = '-'.join(url_part_list)
57 
58     level_id = int(kwargs.get('level_id'))
59     if level_id == 0:
60         pass
61     else:
62         q['level'] = level_id
63 
64     # models.Video.objects.filter(status=1)
65     video_list = models.Video.objects.filter(**q).values('title','summary', 'img', 'href')
66 
67 
68     # level_list = models.Video.level_choice
69 
70     ret = map(lambda x:{"id": x[0], 'name': x[1]}, models.Video.level_choice)
71     level_list = list(ret)
72     return render(request, 'video.html', {'direction_list': direction_list,
73                                           'class_list': class_list,
74                                           'level_list': level_list,
75                                           'current_url': request_path,
76                                           "video_list": video_list})
views
{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        a{
            display: inline-block;
            padding: 8px;
        }
        .active{
            background-color: coral;
            color: white;
        }
        .item{
            display: inline-block;
            width: 300px;
            height: 400px;
        }
        .item img{
            border: 0;
            width: 300px;
            height: 280px;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <h3>选择:</h3>
    <div>
        {% action_all current_url 1 %} :
        {% for item in direction_list %}

             {% action1 current_url item %}
        {% endfor %}
    </div>
    <div>
        {% action_all current_url 2 %} :
        {% for item in class_list %}

            {% action2 current_url item %}
        {% endfor %}
    </div>
    <div>
        {% action_all current_url 3 %} :
        {% for item in level_list %}
            {% action3 current_url item %}
        {% endfor %}
    </div>
    <hr />
    <div>
video.html
from django import template
from django.utils.safestring import mark_safe
from django.template.base import Node, TemplateSyntaxError

register = template.Library()
@register.simple_tag
def action1(current_url, item):
    # videos-0-0-1.html
    # item: id name
    # video-   2   -0-0.html
    url_part_list = current_url.split('-')

    # 如果当前url中第一个位置 video-2-0-0.html
    if str(item['id']) == url_part_list[1]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"

    url_part_list[1] = str(item['id'])

    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)
@register.simple_tag
def action2(current_url, item):
    # videos-0-0-1.html
    # item: id name
    url_part_list = current_url.split('-')

    # 如果当前url中第一个位置 video-2-0-0.html
    if str(item['id']) == url_part_list[2]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"


    url_part_list[2] = str(item['id'])
    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)

@register.simple_tag
def action3(current_url, item):
    # videos-0-0-1.html
    # item: id name
    url_part_list = current_url.split('-')
    # 如果当前url中第三个位置 video-2-0-0.html
    if str(item['id']) == url_part_list[3].split('.')[0]:
        temp = "<a href='%s' class='active'>%s</a>"
    else:
        temp = "<a href='%s'>%s</a>"

    url_part_list[3] = str(item['id']) + '.html'

    ur_str = '-'.join(url_part_list)
    temp = temp %(ur_str, item['name'])
    return mark_safe(temp)

@register.simple_tag
def action_all_1(current_url):
    """
    获取当前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')
    if url_part_list[1] == "0":
        temp = "<a href='%s' class='active'>全部</a>"
    else:
        temp = "<a href='%s'>全部</a>"


    url_part_list[1] = "0"
    #  video 0 1 2.html
    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)

@register.simple_tag
def action_all_2(current_url):
    """
    获取当前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')

    if url_part_list[2] == "0":
        temp = "<a href='%s' class='active'>全部</a>"
    else:
        temp = "<a href='%s'>全部</a>"

    url_part_list[2] = "0"
    #  video 0 1 2.html
    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)

@register.simple_tag
def action_all_3(current_url):
    """
    获取当前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')
    #  video 0 1 2.html
    if url_part_list[3] == "0.html":
        temp = "<a href='%s' class='active'>全部</a>"
    else:
        temp = "<a href='%s'>全部</a>"

    url_part_list[3] = "0.html"

    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)

@register.simple_tag
def action_all(current_url,index):
    """
    获取当前url,video-1-1-2.html
    :param current_url:
    :param item:
    :return:
    """
    url_part_list = current_url.split('-')
    if index == 3:
        if url_part_list[index] == "0.html":
            temp = "<a href='%s' class='active'>全部</a>"
        else:
            temp = "<a href='%s'>全部</a>"

        url_part_list[index] = "0.html"
    else:
        if url_part_list[index] == "0":
            temp = "<a href='%s' class='active'>全部</a>"
        else:
            temp = "<a href='%s'>全部</a>"

        url_part_list[index] = "0"


    href = '-'.join(url_part_list)

    temp = temp % (href,)
    return mark_safe(temp)
xx.py

 

posted @ 2017-04-12 17:23  失落的黎明  阅读(722)  评论(0编辑  收藏  举报