You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板无法始终显示登录用户头像问题求助

问题解决:始终显示当前登录用户的头像

问题原因

你的问题源于模板变量冲突:

  • 在首页或自身资料页时,user_profile变量指向当前登录用户的Profile实例
  • 进入他人资料页时,profile视图将user_profile赋值为被访问用户的Profile,导致header中的头像被替换成他人的

解决方案

方案1:模板直接通过request.user获取自身头像

无需依赖视图传递的user_profile,直接从登录用户的关联Profile中取头像,确保所有页面都显示当前用户的头像:

修改header.html代码:

<div><b><a href="{% url 'index' %}">Bondly</a></b></div>
{% if user.is_authenticated %}
<div>
    <img src="{{ user.profile.img_profile.url }}" />
</div>
{% endif %}
</header>

注:Django中若Profile与User是一对一关联(推荐配置,见下方优化),可直接通过user.profile反向获取关联实例。若未设置related_name,默认以模型名小写作为反向关联名称。

方案2:视图中传递当前登录用户的Profile变量

若不想修改模板,可在所有视图(包括profile视图)中添加当前登录用户的Profile到context,并用独立变量名区分:

修改views.py的profile函数:

def profile(request, pf):
    user_object = User.objects.get(username=pf)
    visited_user_profile = models.Profile.objects.get(usr=user_object)
    # 获取当前登录用户的Profile
    current_user_profile = models.Profile.objects.get(usr=request.user)
    
    # 其余逻辑保持不变...
    
    context = {
        'user_object': user_object,
        "visited_user_profile": visited_user_profile,  # 修改变量名避免冲突
        "current_user_profile": current_user_profile,  # 添加当前用户的Profile
        "posts": posts,
        'postsNum': postsNum,
        "text": text,
        "followers": followers,
        "following": following
        }
    return render(request, 'profile.html', context)

同步修改header.html:

<div><b><a href="{% url 'index' %}">Bondly</a></b></div>
{% if user.is_authenticated %}
<div>
    <img src="{{ current_user_profile.img_profile.url }}" />
</div>
{% endif %}
</header>

额外优化:Profile模型改用OneToOneField

你的Profile模型使用ForeignKey(User),但一个User应对应唯一的Profile,改用OneToOneField更合理,能避免一个User关联多个Profile的异常情况:

修改models.py:

class Profile(models.Model):
    usr = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    id_usr: int = models.IntegerField()
    Fname:str = models.TextField(blank=True,null=True)
    Mname:str = models.TextField(blank=True,null=True)
    Lname:str = models.TextField(blank=True,null=True)
    Fhone:int = models.IntegerField(blank=True,null=True)
    bio: str = models.TextField(blank=True)
    img_profile = models.ImageField(
        upload_to='ProfileIMG', default="blankprofile.png")
    location: str = models.CharField(max_length=250)

    def __str__(self):
        return self.usr.username

修改后执行数据库迁移,即可稳定通过request.user.profile获取当前登录用户的Profile。

内容的提问来源于stack exchange,提问作者Sahil Singhai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:50:21