1

What I'd like to do is using filter() in django template like belows:

models.py

from django.db import models
From Django. utils import Timezone

class Category(models.Model):
    url = models.CharField(max_length=200)
    site_name = models.CharField(max_length=50)
    board_name = models.CharField(max_length=50)

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField(blank=True)
    category = models.ForeignKey(Category)
    created_date = models.DateField(blank=True, null=True)
    crawl_date = models.DateTimeField()
    num_of_comments = models.PositiveSmallIntegerField(default=0, blank=True, null=True)
    notice = models.BooleanField(default=False)

views.py

def post_list(request, site_name=None, page=1):
    categories = Category.objects.filter(site_name=site_name.upper()).order_by('board_name')
    return render(request, 'SNU/post_list.html', {'site_name':site_name.upper(), 'categories':categories})

post_list.html

{% for category in categories %}
    <p> {{category}} </p>
    {% for post in category.post_set.filter(notice=True) %}
        <li>{{ post.title }}</li>
    {% endfor %}
{% endfor %}

In post_list.html, {% for post in category.post_set.filter(notice=True) %} occurs error. Only category.post_set.all is the one that I can use in template?

user3595632
  • 5,380
  • 10
  • 55
  • 111
  • Possible duplicate of [How to call function that takes an argument in a Django template?](http://stackoverflow.com/questions/2468804/how-to-call-function-that-takes-an-argument-in-a-django-template) – rafalmp Jul 07 '16 at 00:13

1 Answers1

1

You can do it on view level by

def post_list(request, site_name=None, page=1):
    categories = Category.objects.filter(site_name=site_name.upper(),
                                         notice=True).order_by('board_name')
    return render(request, 'SNU/post_list.html',{'site_name':site_name.upper(), 
                'categories':categories})

If for some reason you need all categories, not just those having notice = True, add one more query without notice=True in filter and pass it in the dictionary.

Alternatively, you can create custom tag and provide filter - see https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

dmitryro
  • 3,463
  • 2
  • 20
  • 28
  • You can't use filter in template itself, so you have to create a template tag like in the link above, or pass posts as a separate parameter. basically you can design a tag {% get_posts category_id %} and iterate – dmitryro Jul 07 '16 at 00:38
  • Here's more on this http://stackoverflow.com/questions/6451304/django-simple-custom-template-tag-example – dmitryro Jul 07 '16 at 00:40
  • If you need to chain the category and post you can use https://github.com/digi604/django-smart-selects – dmitryro Jul 07 '16 at 00:42
  • Custom tags are heled ! Thanks :) – user3595632 Jul 07 '16 at 02:23