我在django 3中建立了一个博客,我想把所有的文章按作者过滤,并在作者页面显示结果。我似乎想不通我的代码有什么问题。请大家帮忙。如果我可以得到一个解释,我的代码有什么问题,那将是感激的。
视图.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
模型.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)
模板
{% for object in authorpost_list %}
{{ object.title }}
{% endfor %}
urls.py
urlpatterns = [
path('author_post/', views.AuthorPostListView.as_view(), name = 'author_posts'),
]
你用get context数据覆盖了你想要的实际视图,所以你可以去掉get context方法,在模板中调用作为
{% for object in object_list %}
{{ object.title }}
{% endfor %}
或者你可以做
context['authorpost_list'] = Post.objects.filter(author = self.request.user).order_by('-created_on')
并以同样的方式调用模板。