在Djang的/author/admin/处出现值错误

2024-04-20 05:02:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下博客项目:

网址.py形态:

  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)

模板/posts/getAllPosts

<a href={% url 'grabAuthorPosts' author=post.author.username %}>
{{post.author}}</a>

我正在尝试这样做,当点击post.author链接时,用户将被带到一个包含与特定作者相关的帖子的页面。链接公式本身看起来还可以,因为当点击管理员创建的帖子时,url会显示localhost/author/admin/

我认为我的问题在于如何让上下文变量author_posts工作。我刚来Django,所以非常感谢您的解释。你知道吗

latest_posts以及author=False在模板中的其他地方用于获取所有文章,而不管作者是谁,这很好。你知道吗

错误是:

ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'

Tags: selftrueurldatetitlemodelspostlatest