更改django-allauth render_authentication_error行为

Fel*_* D. 5 python django django-allauth

我是python/Django宇宙的新手,刚刚开始了一个我非常兴奋的大项目.我需要让我的用户通过Facebook登录,我的应用程序有一个非常具体的用户流程.我已经建立了django-allauth,一切都按照我的需要运作.我已经覆盖了LOGIN_REDIRECT_URL,以便我的用户在登录时登陆我想要的页面.

但.当用户打开Facebook登录对话框然后关闭它而不登录时,authentication_error.html模板将被渲染allauth.socialaccount.helpers.render_authentication_error,这不是我想要的行为.我希望用户只需重定向到登录页面.

是的,我知道我可以通过将模板放在我的模板中来覆盖模板TEMPLATE_DIRS,但之后网址将不一样.

我得出结论我需要一个中间件来拦截对http请求的响应.

from django.shortcuts import redirect

class Middleware():
    """
    A middleware to override allauth user flow
    """
    def __init__(self):
        self.url_to_check = "/accounts/facebook/login/token/"

    def process_response(self, request, response):
        """
        In case of failed faceboook login
        """
        if request.path == self.url_to_check and\
                not request.user.is_authenticated():
            return redirect('/')

        return response 
Run Code Online (Sandbox Code Playgroud)

但我不确定我的解决方案的效率,也不确定pythonesquitude(我是juste想出了那个词).在没有使用中间件或信号的情况下,我还能做些什么来改变默认的django-allauth行为?

谢谢!

Fel*_* D. 0

我决定使用中间件并重定向到主页 url,以防对表单的 URL 发出 GET 请求^/accounts/.*$

from django.shortcuts import redirect
import re


class AllauthOverrideMiddleware():
    """
    A middleware to implement a custom user flow
    """
    def __init__(self):
        # allauth urls
        self.url_social = re.compile("^/accounts/.*$")

    def process_request(self, request):

        # WE CAN ONLY POST TO ALLAUTH URLS
        if request.method == "GET" and\
           self.url_social.match(request.path):
            return redirect("/")
Run Code Online (Sandbox Code Playgroud)