Django: How to filter and display categories for author in post I guess there's something wrong with the get_queryset Category.objects.filter(post_author=username)
class Post(models.Model):
exercisename = models.ForeignKey('Category', on_delete=models.CASCADE)
hour = models.IntegerField(default=0 )
min = models.IntegerField(default=0)
file = models.FileField(null=True,blank=True,upload_to='Files')
content = models.TextField()
date_Posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='images/')
def userpost(request, username):
context = {
'Category': Category.objects.filter(post_author=username),
}
return render(request, 'blog/user_Posts.html', context)
CodePudding user response:
first you need to have a relation between Post and Catagory inorder to make the query works!!
class Post(models.Model):
exercisename = models.ForeignKey('Category', on_delete=models.CASCADE)
hour = models.IntegerField(default=0 )
min = models.IntegerField(default=0)
file = models.FileField(null=True,blank=True,upload_to='Files')
content = models.TextField()
date_Posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='images/')
def userpost(request, username):
#this gives the username's posts and change the django query result to a python list
# a list of catagories
author_posts_catagories = Post.objects.filter(author=username).values_list('category',flat=True)
context = {
# this gives you the selected user catagories from post
'Category':Category.objects.filter(id__in = author_posts_catagories ) ,
}
return render(request, 'blog/user_Posts.html', context)
CodePudding user response:
You should filter your category like this:
Category.objects.filter(post_author__username=username)
When you call ForeignKey
directly, it expects object, not field. So you use __{field_name}
to call exact field in Django ORM.
Also, your category has no relation to Post
model, or has Author
relation at all...