有没有办法将自定义代码添加到 login_required

Is there a way to add custom code to login_required

我自己做了 LoginRequiredMixin 这样的:

class LoginRequiredMixin(object):
    @classmethod
    def as_view(cls, **initkwargs):
        view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        # (!!) multilangue = reverse_lazy, PAS reverse
        return login_required(view, login_url=reverse_lazy('my_home_login'))

到目前为止一切顺利,当您像这样创建新视图时一切正常:

class EditView(LoginRequiredMixin, generic.UpdateView):
    model = Personne
    template_name = 'my_home/profile/base.html'
    form_class = ProfileForm
    success_url = reverse_lazy('my_home_profile_edit')

等等。

现在,我的客户要求我实现一个选项:如果用户想删除他的帐户,我必须将其标记为 "inactive",发送一封重新激活的电子邮件 link有效期为 15 天,如果用户尝试在这 15 天内登录 而没有 单击重新激活 link,我应该显示一条消息说 "your account has been disabled, please click on the link we sent".

所以我想在用户登录后实现"inactive"帐户,并显示"your account is disabled"消息。因为我想在 URL 中显示它(我的个人资料、我的旅行、我的好友、我的消息或其他),所以我应该在 LoginRequiredMixin class 中显示它。问题是:我不知道该怎么做。例如,我需要覆盖所有 template_name(如果有的话),并禁止所有操作但显示消息。

怎么做?

看起来 request/response 中间件是检查这个的更好地方,不是吗?在那里你可以检查用户是否已经登录以及它是否被禁用。并在那里进行大量数据操作。

至于我,它实际上不需要登录,因为用户已经登录。看起来最好将您的登录名放入中间件。例如,如果您使用默认的用户模型选项 is_active,您可以检查它(或任何其他标志)并将用户重定向到每个请求的某个模板,在那里您要求它激活其帐户。

例如,您可以像这样制作中间件:https://djangosnippets.org/snippets/510/ 这是中间件的 Django 文档,具有非常干净的请求处理模式:https://docs.djangoproject.com/en/1.9/topics/http/middleware/ 其他教程:http://www.webforefront.com/django/middlewaredjango.html 看起来它对每个方法的实际作用都有非常清晰的注释。 以下是设置自定义中间件的方法:how to setup custom middleware in django