我一直试图让用户的个人资料页面包含用户的帖子,但每次我运行代码时,都没有显示任何内容,只有用户的用户名和用户的电子邮件。我尝试了多种方法使它工作,但不知为什么它没有。我认为profile.html中有错误
views.py
def profile(request, pk=None):
if pk:
post_owner = get_object_or_404(User, pk=pk)
user_posts=Post.objects.filter(posti=request.user)
else:
post_owner = request.user
user_posts=Post.objects.filter(posti=request.user)
return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts})
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
posti = models.ImageField(upload_to='media/images', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default=2)
profile.html
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ post_owner.username }}</h2>
<p class="text-secondary">{{ post_owner.email }}</p>
</div>
{% for Post in user_posts %}
<li class="list-group-item">{{ Post.text }}
<a href="{% url 'profile_pk' pk=image.user.pk %}">{{ Post.user }}</a>
{% if Post.posti %}
<img src="{{ image.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px">
{% endif %}
{% if Post.user == user %}
<div class="float-right">
<form action="delete_image/{{ image.id }}/" action="post">
<button type="submit" class="btn btn-outline-danger btn-sm">Delete</button>
</form>
</div>
{% endif %}
</li>
{% endfor %}
</div>
</div>
您查询的列不正确:
posti
是一个ImageField
。您实际上想要查询user
字段:也就是说,在视图中不需要任何这些查询。您只需使用
related_name
,即:这里的问题在于线路:
要从登录用户处获取帖子,您需要使用以下命令:
要从所选用户获取帖子,您需要执行以下操作:
我希望这有帮助:)
相关问题 更多 >
编程相关推荐