Search code examples
djangodjango-templatesdjango-viewsfeincms

download list with category ManyToManyField


I like a download list with all Files with the Category == 'download' in all available categories. (ManyToMany Field)

>>>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

it must be a mix from :

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

but not all files, only the files with the category (or let's say Tag) 'download'.

and:

{% 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>

these files are good, but the categories are not in the right position and format.

I need a tree like this:

Category 1 # the Download category, all files

  • file 3
  • file 1
  • file 2

Category 2

  • file 3

Category 3

  • |_ SubCategory 3.1 (if chidren, next challenge)
    • file 2
  • file 3

my views.py this:

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))

I'm a beginner, maybe it is very easy...


Solution

  • You can use self referential template includes, and then just pass the categories variable in as the current children of each category as you iterate through..

    Lets say this is: 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>