X
X
xxx2017-08-16 15:34:38
Django
xxx, 2017-08-16 15:34:38

Can you help me sort out the categories?

So I have 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)

What should I write in the templates so that by clicking on a category, I will only see posts with this category (filter)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sergeev, 2017-08-16
@Heavy10110

views.py

def category(request, slug):
    context = {
        'posts': Post.objects.filter(category__slug=slug)
    }
    return render(request, 'category.html', context)

And in the template
{% for post in posts %}
{{ post }}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question