首页 > 解决方案 > 如何从用户模型访问在 Django 中使用 google 登录的用户的用户名

问题描述

如何从用户模型访问在 django all-auth 中使用 google 登录的用户的用户名

例如,我如何从用户模型中使用 google 访问登录用户的用户名

{% for i in user %}
    {{i.socialaccount_set.all.0.extra_data.name}}//is there a way to acces the user name in this way
{% endfor %}

我的观点.py

def leaderBoard(request):
points= Points.objects.all().order_by("-score")
context = {"user": result}
return render(request, "Main/lb.html", context)

我的模型.py

class Points(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    score = models.BigIntegerField()

我的html文件

<div class="leaderboard-table">
    {% for i in user %}
    <div class="board-item">
      <div>1</div>
      <div>
        {% if i.socialaccount_set.all.0.get_avatar_url %}
        <img src="{{i.socialaccount_set.all.0.get_avatar_url}}" />
        {{i}}//how to access the user name of the googleuser
      </div>
      <div>Test's Taken - 30</div>
      <div>{{i.score}} Points</div>
    </div>
    {% endfor %}
  </div>

在此处输入图像描述

标签: pythondjangodatabase

解决方案


使用用户名,我假设您想访问该特定用户的 Django 的默认用户名字段。

您可以像这样访问它。

{% for i in user %}
    {{i.username}}
{% endfor %}

另外,我注意到的另一件事是您的视图缺少result您要附加到上下文字典的数据。


推荐阅读