类别为 ManyToManyField 的下载列表

download list with category ManyToManyField

我喜欢一个下载列表,其中包含所有可用类别中类别 == 'download' 的所有文件。 (多对多字段)

>>>from feincms.module.medialibrary.models import MediaFile, Category
>>>MediaFile.objects.filter(categories=1) #my download pk, these files I need
>>>Category.objects.all() # these categories I need

models.py: https://github.com/feincms/feincms/blob/master/feincms/module/medialibrary/models.py

它必须是来自 :

的混合
{% for category in category %}
<h1>{{ category }}</h1>
    {% for file in category.mediafile_set.all %}
        <li> {{ file }} </li>
    {% endfor %}
 {% endfor %}

但不是所有文件,只有类别(或者说标签)'download'.

的文件

和:

{% regroup file by categories.all as media_list %}
<ul>
{% for categories in media_list %}
    <li>{{ categories.grouper }}
    <ul>
        {% for file in categories.list %}
          <li>{{ file }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

这些文件都不错,但类别位置和格式不对。

我需要这样一棵树:

类别 1 # 下载类别,所有文件

类别 2

类别 3

我的views.py这个:

from feincms.module.medialibrary.models import MediaFile, Category

def medialistview(request):
    file = MediaFile.objects.filter(categories=1)
    category = Category.objects.all()   
    return render_to_response('media.html',{
        'file': file, 'category': category, 
    },context_instance=RequestContext(request))

我是初学者,也许很容易...

您可以使用自引用 template includes,然后在遍历时将 categories 变量作为每个类别的当前子级传入..

假设这是:category_tree.html

{% regroup file by categories.all as media_list %}
<ul>
{% for category in media_list %}
    <li>{{ category.grouper }}
    {% include "category_tree.html" with categories=category.children %}
    <ul>
        {% for file in category.list %}
          <li>{{ file }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>