我有以下博客项目:
urls.py conf:
url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts')
帖/模型:
class Post(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=500, default = True)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
author = models.ForeignKey(User, default=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
帖/视图:
def getAllPosts(request, author=False):
latest_posts = Post.objects.all().order_by('-pub_date')
comments = Comment.objects.all().order_by('-pub_date')
author_posts = User.objects.get(id=author)
author_posts = author_posts.post_set.all()
context = {
'latest_posts':latest_posts,
'comments':comments,
'author_posts':author_posts
}
return render(request, 'posts/getAllPosts.html', context)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
模板/帖/ getAllPosts :
<a href={% url 'grabAuthorPosts' author=post.author.username %}>
{{post.author}}</a>
我正在尝试这样做,以便在点击post.author
链接时,用户将被带到包含与该特定作者相关的帖子的页面。链接制定本身似乎没问题,因为当点击管理员创建的帖子时,网址会显示localhost/author/admin/
我相信我的问题在于让上下文变量author_posts
起作用。我是Django的新手,所以任何解释都非常感激。
latest_posts
以及author=False
在模板的其他位置用于获取所有帖子,无论作者如何,这都可以。
错误是:
ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'