[英]Django blog post by authors
I am building a blog in django 3. I want to filter all posts by author and display the results in author page.我正在 django 3 中建立一个博客。我想按作者过滤所有帖子并在作者页面中显示结果。 I can't seem to figure what is wrong with my code.
我似乎无法弄清楚我的代码有什么问题。 Please help.
请帮忙。 If i can get an explaination on what is wrong with my code, that will be appreciated.
如果我能解释我的代码有什么问题,那将不胜感激。
Views.py视图.py
class AuthorPostListView(ListView):
model = Post
paginate_by = 5
template_name = 'author_post.html'
def get_queryset(self):
return Post.objects.filter(author = self.request.user).order_by('created_on').reverse()
def get_context_data(self):
context = super(AuthorPostListView, self).get_context_data(**kwargs)
context['authorpost_list'] = Post.objects.all()
return context
Models.py模型.py
class Post(models.Model):
title = models.CharField(max_length=200)
post_slug = models.SlugField(max_length = 200, unique = True)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now = True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name = 'blog_posts',
)
post_picture = models.ImageField(
upload_to = 'post_picture',
null = True,
blank = True,
default='/media/post_picture/2.jpg',
)
approved_comment = models.BooleanField(default=True)
tags = TaggableManager()
categories = models.ManyToManyField('Category', related_name = 'posts')
def approve(self):
self.approved_comment = True
self.save()
class Meta:
ordering = ['created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
Template模板
{% for object in authorpost_list %}
{{ object.title }}
{% endfor %}
urls.py网址.py
urlpatterns = [
path('author_post/', views.AuthorPostListView.as_view(), name = 'author_posts'),
]
you are over-riding the actual view you wanted with get context data, so you can remove the get context method and call in the template as您正在使用获取上下文数据覆盖您想要的实际视图,因此您可以删除获取上下文方法并在模板中调用
{% for object in object_list %}
{{ object.title }}
{% endfor %}
or you can do或者你可以做
context['authorpost_list'] = Post.objects.filter(author = self.request.user).order_by('-created_on')
and call in template in the same way as you shown并以与您显示的方式相同的方式调用模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.