我想创建一个 user_posts 视图,其中包含与特定用户相关的所有帖子让我们说有/有用户“Natsu”写的博客帖子然后登录用户让我们说“Testuser”将能够看到所有帖子由该用户即用户“Natsu”的所有帖子。
blog models.py
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
user models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pic', default='default.jpg')
def __str__(self):
return f'{ self.user.username } Profile'
views.py
def user_posts(request, username):
posts = Post.objects.filter(author=username)
return render(request, 'blog/user_posts.html', {'posts':posts})
user_posts.html
{% for post in posts %}
<a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a>
<h2><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></h2>
{{ post.body|truncatewords:30 }}
{% endfor %}
urls.py
path('user/<str:username>/', views.user_posts, name='user-posts'),
但是当我访问那个 url 时它显示错误Field 'id' expected a number but got 'admin'.
有只小跳蛙
翻阅古今
回首忆惘然
相关分类