Is there a way to add custom code to login_required

岁酱吖の 提交于 2019-12-12 04:04:47

问题


I've made my own LoginRequiredMixin like this:

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'))

So far so good, everything works fine when you create new views like this:

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')

and so on.

Now, my client asked me to implement an option: if the user wants to delete his account, I have to mark it as "inactive", sends an email with a re-activation link that is valid for 15 days and if the user tries to login in within those 15 days without having clicked on the re-activation link, I should display a message saying "your account has been disabled, please click on the link we sent".

So I want to implement the "inactive" account after the user is logged in, and display the "your account is disabled" message. Because I want to display it whatever the URL is (my profile, my travels, my buddies, my messages or whatever), I should do it in the LoginRequiredMixin class. The problem is: I dont know how to do it. For example, I need to override all template_name if there's one, and forbid every action but display the message.

How to do it?


回答1:


Looks like request/response middleware is better place to check this, isn't it? There you can check if user is already logged in and if it is disabled. And make a lot of data manipulations there.

As for me, it is not actually login required, since user is already logged in. It loooks like it is better to place your login into middleware. For example, if you use default Users model option is_active, you can check it (or any other flag) and redirect user to some template for each reaquest, where you asking it to activate its account.

For example you can make you middleware like this: https://djangosnippets.org/snippets/510/ Here is the django documentation for middlewares with very clean schema of request handling: https://docs.djangoproject.com/en/1.9/topics/http/middleware/ Other tutorial: http://www.webforefront.com/django/middlewaredjango.html Looks like it has very clean comments about what each method actually does. Here is how to setup your custom middleware: how to setup custom middleware in django



来源:https://stackoverflow.com/questions/35337120/is-there-a-way-to-add-custom-code-to-login-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!