【问题标题】:Django @decorator for UserProfile allauthDjango @decorator for UserProfile allauth
【发布时间】:2014-03-15 05:43:58
【问题描述】:

我目前正在使用 allauth 包,它扩展了用户模型以包含附加字段,例如 about me。我想知道是否有任何类似于登录的方法可以使用@decorator 来检查User.profile。代码如下所示,我认为它比我能解释得更好。

我正在尝试@user_passes_test(lambda u: u.profile.account_verified),它总是返回<bound method UserProfile.account_verified of <UserProfile>>

型号:

class UserProfile(models.Model):
  user = models.OneToOneField(User, related_name='profile')
  about_me = models.TextField(null=True, blank=True)

  def account_verified(self):
      """
      If the user is logged in and has verified hisser email address, return True,
      otherwise return False
      """
      if self.user.is_authenticated:
          result = EmailAddress.objects.filter(email=self.user.email)
          if len(result):
              return result[0].verified
      return False

查看:

@user_passes_test(lambda u: u.profile.account_verified)
def index(request):
  //logic in here

【问题讨论】:

    标签: python django decorator django-allauth


    【解决方案1】:

    它返回一个绑定的方法对你来说应该是一个巨大的提示:它是一个方法,而不是一个值。你通常调用方法来让它完成它的工作,所以你缺少的是调用它。

    @user_passes_test(lambda u: u.profile.account_verified)
    

    如果 lambda 函数返回 bool(function_result) 为 true,则此测试通过:对于方法,它始终为 true。

    你想要的是调用该方法并让它返回一个真或假

    @user_passes_test(lambda u: u.profile.account_verified())
    

    或者如果你想让方法成为一个属性,用@property装饰方法

      @property
      def account_verified(self):
    

    现在它是一个属性,你不需要调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 2012-11-18
      • 1970-01-01
      • 2014-08-30
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多