编辑: 这是我的视图和我的模型和Html。我正在尝试在django中创建用户个人资料页面。我需要查询并在配置文件页面中仅提取request.user的信息。问题似乎是我无法获得正确的查询过滤器。
class UserView(generic.ListView):
model = Post
template_name = 'post/user_page.html'
context_object_name = 'all_post'
def get_queryset(self):
return Post.author.all()
class Post(models.Model):
creator = models.CharField(max_length=250)
post_name = models.CharField(max_length=250)
category = models.CharField(max_length=250)
post_photo = models.FileField()
author = models.ForeignKey(User, blank=True, null=True, related_name ='user_post')
category = models.ManyToManyField(Category)
def get_absolute_url(self):
return reverse('post:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.creator + ' - ' + self.post_name
<div class="col-sm-6 col-sm-offset-3">
<div class="roote-container container-fluid">
<h1>Welcome {{user.username}}</h1>
<div class="row">
{% for post in all_post %}
<div class= col-sm-12">
<div class="thumbnail">
<!--Post Photo-->
<a href="{% url 'post:detail' post.id %}" >
<img src="{{ post.post_photo.url }}" class="img-responsive">
</a>
<div class="caption">
<h2>{{ post.post_name }}</h2>
<p>{{ post.user }}</p>
<!-- Details-->
<a href="{% url 'post:detail' post.id %}"class="btn btn-primary">{{post.posts_name}} post</a>
<!--delete-->
<form action="{% url 'post:post-delete' post.id %}" method="post" style="display inline;">
{% csrf_token %}
<input type="hidden" name="post_id" value="{{ post.id }}"/>
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
答案 0 :(得分:2)
什么是Post.author.all()?
如果您需要特定作者的所有帖子,请执行
Post.objects.filter(author__username= 'name of author')
其中name是作者模型中的字段。
或者如果你想要所有作者的所有帖子
Post.objects.all().select_related('author')
答案 1 :(得分:0)
其他答案都很好,但我认为,由于您已定义related_name ='user_posts'
,因此检索与User实例对应的帖子的更好方法是根据related_name
字段执行此操作:
user_posts = <the user>.blog_posts.all()