检查用户是否在 Django 模板中订阅了 dj-stripe

Check if a user has a subscription with dj-stripe in Django templates

我希望在许多不同的 Django 模板中有一个按钮,鼓励用户订阅两个 dj-stripe 付费计划之一,但我不想向已经订阅的用户显示该按钮任何一个计划。

我知道我可以在模板中使用 {% if user.is_authenticated %}。我还没有找到类似的东西来检查用户是否订阅了 dj-stripe 计划。有什么东西吗?如果有,那是什么东西?如果没有,我该如何在不重复的情况下处理这个问题?

我同意@nnaelle 的观点,向您的用户模型添加 is_subscribed 属性是确保订阅按钮不会显示给已订阅用户的好选择。添加此属性意味着,如果您还没有,则需要在 models.pyextend the user model 以跟踪他们是否已订阅。这看起来像这样(如 Django 文档中所示):

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    is_subscribed = models.BooleanField(default=False)

然后可以通过 views.py:

中的视图访问新的用户模型
from my_app.models import UserProfile

def index(request):
    user = request.user
    userprofile = UserProfile.objects.get(user=user)
    ...

您可以(并且可能希望)避免以这种方式访问​​用户配置文件,但是,通过在 settings.py 下将您的新用户模型设置为应用程序的默认模型,如 [= 的文档中所述19=]。然后在将新用户模型传递给视图后,您可以使用 {% if not userprofile.is_subscribed %} 检查订阅状态,并只为未订阅的用户显示订阅按钮:

{% if not userprofile.is_subscribed %}
    <div ...></div>
{% endif %}

欢迎随时给我反馈!

事实证明已经有 a dj-stripe solution to this(我在 Google 搜索中没有找到)。

我刚刚将其添加到我的扩展用户模型中:

def __str__(self):
    return self.username

def __unicode__(self):
    return self.username

@cached_property
    def has_active_subscription(self):
        """Checks if a user has an active subscription."""
        return subscriber_has_active_subscription(self)

然后将其添加到我的模板中:

{% if request.user.has_active_subscription %}
    <a href="/payments/history/">Subscription History</a>
{% else %} 
    <a href="/payments/subscribe/">Upgrade to Premium Content!</a>
{% endif %}