Python 显示用户';s在django的个人资料中发布的帖子
我一直试图让用户的个人资料页面包含用户的帖子,但每次我运行代码时,都没有显示任何内容,只有用户的用户名和用户的电子邮件。我尝试了多种方法使它工作,但不知为什么它没有。我认为profile.html中有错误 views.pyPython 显示用户';s在django的个人资料中发布的帖子,python,html,django,django-models,Python,Html,Django,Django Models,我一直试图让用户的个人资料页面包含用户的帖子,但每次我运行代码时,都没有显示任何内容,只有用户的用户名和用户的电子邮件。我尝试了多种方法使它工作,但不知为什么它没有。我认为profile.html中有错误 views.py def profile(request, pk=None): if pk: post_owner = get_object_or_404(User, pk=pk) user_posts=Post.obje
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>
{{post_owner.username}
{{post_owner.email}
{用户_posts%}中的Post为%
{{Post.text}
{%if Post.posti%}
{%endif%}
{%if Post.user==user%}
删除
{%endif%}
{%endfor%}
这里的问题在于线路:
user_posts=Post.objects.filter(posti=request.user)
要从登录用户处获取帖子,您需要使用以下命令:
user_posts=Post.objects.filter(user=request.user)
要从所选用户获取帖子,您需要执行以下操作:
user_posts=Post.objects.filter(user_id=pk)
我希望这有帮助:)您查询的列不正确:
user_posts=Post.objects.filter(posti=request.user)
posti
是一个ImageField
。您实际上想要查询用户
字段:
user_posts=Post.objects.filter(user=request.user)
也就是说,在视图中不需要任何这些查询。您只需使用您的相关名称
,即:
{% for Post in post_owner.imageuser.all %}
soory,你说的相关名称是什么意思?在你的模型中,
related\u name='imageuser'
看到一个NoReverseMatch错误是因为你的url.py
中没有与你所查找的内容相匹配的url。这很可能是由于以下代码:{%url'profile\u pk'pk=image.user.pk%}
。这可能是{%url'profile\u pk'pk=Post.user.pk%}
因为image
实际上没有在模板中的任何地方定义。您的代码正在工作,但用户的配置文件页面显示登录用户的帖子,而不是所选用户的帖子。我认为profile.html上有一个if语句错误,它从正在检查的用户中选择帖子。啊,好的。我已经更新了我的答案,以便更清楚地了解如何从不同的用户那里获取帖子。蒂姆,只有一个问题。当我尝试删除图像时,它在纵断面图上不起作用,但在imagelist视图上起作用,该视图显示所有用户的所有图像,如果您需要查看更多代码,如imagelist视图或delete_post,请告诉我。