【问题标题】:How can i get a specific provider from Django social-auth in a template?如何在模板中从 Django social-auth 获取特定的提供者?
【发布时间】:2012-04-04 15:38:44
【问题描述】:

在安装和设置了 social-auth 之后,我正在玩一会儿,试图掌握它的窍门。我已阅读文档,并使用示例项目来运行它。

但直到现在我还不知道如何获取某个提供商的信息。在示例项目中,模板标签总是以这种方式使用:

{% for type, accounts in social_auth.associated.items %}
    {% for account in accounts %}
        {{account.provider}} is connected.
    {% endfor %}
{% endfor %}

我现在要做的不是列出所有提供商,而是检查是否有人将他的帐户连接到(即)facebook。这样我就可以做这样的事情:

if user==connected_to_facebook
    provide some functionality
endif

从上面的示例中,我知道 social_auth.associated.items 包含 (type,account) 的元组,其中“facebook”将出现在包含 account.provider 的所有值的列表中。

我想到的是:

{% if "facebook" in social_auth.associated.items.accounts.provider %}

这显然行不通。我认为这个会起作用,但不会返回我想要的结果:

{% if "facebook" in social_auth.associated.items[1].provider %}

Django 中是否有一些我可以使用的功能?也许我缺少一些特殊的模板标签?或者这个功能是否已经内置到 social_auth 中,我不知何故错过了文档?或者,我最怀疑的是,它真的很明显吗,我只是......

非常欢迎任何帮助。

【问题讨论】:

    标签: django django-socialauth


    【解决方案1】:

    “social_auth”不是元组中的一些元组,它是一个字典:

    {'not_associated': {}, 'backends': {'oauth2': ['facebook']},
     'associated': {'oauth2': [<UserSocialAuth:testuser>]}}
    

    这当然更有意义,但仍然没有任何结果。因此,我查看了一个尚未关联其帐户的用户,该字典如下所示:

    {'not_associated': {'oauth2': ['facebook']}, 'backends': {'oauth2': ['facebook']},
     'associated': {}}
    

    现在我发现了一些有用的东西:

    {% if "facebook" in social_auth.not_associated.oauth2 %}
    {% else %}
        provide facebook functionality
    {% endif %}
    

    这行得通。您只需要知道您正在寻找的后端使用什么类型的身份验证,然后确保它不在 social_auth 的 not_associated 字段中。

    【讨论】:

      【解决方案2】:

      如果有人需要创建断开连接的 URL,这是我想出的 hack-y 代码,其中 providers 是我传递的列表,例如 ["Facebook", "Twitter"]

      {% for p in providers %}
          <h2>Link {{ p }} Account</h2>
          <p>Use your {{ p }} account to log in
          {% if p|lower in social_auth.not_associated %}
              <a href="{% url socialauth_associate_begin p|lower %}?next={{ request.path }}" class="off">No</a>
          {% else %}
              {% for item in social_auth.associated.all %}{% if item.provider == p|lower %}
              <a href="{% url socialauth_disconnect_individual p|lower item.id %}" class="on">Yes</a>
              {% endif %}{% endfor %}
          {% endif %}
          </p>
      {% endfor %}
      

      似乎应该有一个关联帐户的字典而不是这样做,但我想不通。不确定如果用户成功授权他们的帐户两次会发生什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 2014-03-26
        • 2021-11-08
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多