question1 question1 - 2 years ago 87
Python Question

How should I add category in template?

Models:

class Category(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=200, unique=True )

def __unicode__(self):
return self.name

class Post(models.Model):
title = models.CharField(max_length = 100)
content = models.TextField(max_length = 600, default = 'cool' )
date_of_creating = models.DateTimeField(auto_now=False, auto_now_add=True)
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
height_field="height_field",
width_field="width_field"
)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
category = models.ForeignKey('Category')
slug = models.SlugField(unique=True, blank=False)


def __unicode__(self):
return self.title


Views:

def category(reguest, slug):
category = Category.objects.get(slug=slug)
post = Post.objects.filter(category=category)
html = 'category.html'
context = {
'category': category,
'post': post,
}
return render(reguest, html, context)

def listofposts(request):
query_set_list = Post.objects.all()
context = {
"list" : query_set_list,
}
html = 'base.html'
return render(request, html, context)


I dont know what should I write in template to filter my posts by categories.
I need to choose category and display posts of this category. How can I filter it by category?

Answer Source

I believe you are asking how to show your posts, arranged by categories? If that is what you are after, your template should look something like this:

template.html

{% if category %}
{% if post %}
    {% for c in category %}
        {% for p in post %}
            {% if p.category == c %}
                <div>{{ p.title }}</div> <!-- and whatever else you want to display and however you want to style it I am just giving an example -->
            {% endif %}
        {% endfor %}
    {% endfor %}
{% endif %}
{% endif %}

Based on what you do in your views, this is one way to display by category. Note there are better ways of how you can traverse the data, and group them up, but you are asking for this. So I hope this helps you out!

EDIT 1

After reading your question again (i believe there was an edit) I saw that you are asking how to show the posts for the selected category. I am assuming that since you have a slug the category selected is in the URL. So indeed in the view you are selecting the correct posts. So in order to display the posts from the selected category you simply have to do this in your template:

{% if post %}
    {% for p in post %}
        <div>{{ p.title }}</div> <!-- and whatever else you want to display and however you want to style it I am just giving an example -->
    {% endfor %}
{% endif %}

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download