我有一个扩展了 AbstractBaseUser 的用户模型
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True, default='abc123@gmail.com')
forename = models.CharField(max_length=20, default='')
surname = models.CharField(max_length=20, default='')
account_expiry = models.DateField(default=datetime.now() + timedelta(days=365))
在我的所有 View 中,我都使用 LoginRequiredMixin 进行身份验证,例如
class IndexView(LoginRequiredMixin, generic.TemplateView):
我不仅要通过电子邮件和密码对用户进行身份验证,还要通过检查帐户是否已过期。
我的问题是 - 实现此目标的最佳(最简单?)方法是什么。我是否编写自己的自定义身份验证后端 as described here ?或者我应该寻找编写自定义 Mixin 或中间件的方法吗?
最佳答案
所以最后我的解决方案是创建我自己的自定义中间件。
我找到了 How to Create a Custom Django Middleware一个有用的起点,但它对我不起作用,因为我使用的是 Django 2.0.1。 The official docs解释了如何更新解决方案,我还找到了 this SO帖子有用。
所以我的代码看起来像:
class AccountExpiry:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
current_user = request.user
response = self.get_response(request)
expiry_path = reverse('accounts:account-expired')
if current_user.is_anonymous is False:
if current_user.admin is False and current_user.staff is False:
if request.path not in [expiry_path]:
expiry_date = current_user.school.account_expiry
todays_date = datetime.today().date()
if todays_date > expiry_date:
return HttpResponseRedirect(expiry_path)
return response
(请注意,根据我上面的原始问题,account_expiry 实际上是相关表(学校)中的一个字段,而不是用户模型中的一个字段)。
我更新了设置 MIDDLEWARE= 以包含
'common.middleware.AccountExpiry',
它如我所愿地工作。
关于django - 处理 Django 用户订阅到期日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51188439/