身份验证后如何在 django-allauth 中获取 GitHub 用户名?

How get GitHub username in django-allauth after authentication?

我将 django-allauth 添加到 Django 项目,我可以在网站上使用 GitHub 进行身份验证。
用户认证后,我想得到GitHub用户名(登录的用户)。
怎么做?

{% for account in user.socialaccount_set.all %}

    <p>Username: <a target="_blank"
                    href="{{ account.extra_data.html_url }}">{{ account.extra_data.login }}</a>
    </p>

{% endfor %}

extra_data.login - 显示 GitHub 的登录信息。

allauth设置的用户名和github返回的用户名不一样,是函数generate_unique_username返回的值看到是sourcecode,所以你最好访问 SocialAccount 的 extra_data 字段,下面是显示如何访问它的示例视图。

from django.shortcuts import HttpResponse, render
from allauth.socialaccount.models import SocialAccount
def home(request):
    if request.user.is_authenticated:
        try:
            social_account=SocialAccount.objects.get(user=request.user).extra_data
            return HttpResponse(social_account['login'])
        except SocialAccount.DoesNotExist: # user created with email and password
            return HttpResponse(request.user.username)
    return HttpResponse("<a href='/accounts/github/login/'>Sign Up</a>")