2015-02-09 67 views
5

我是Python/Django世界的新手,剛開始一個我很興奮的大項目。我需要讓我的用戶通過Facebook登錄,我的應用程序具有真正特定的用戶流。我設置了django-allauth,一切都按我需要的方式工作。我已覆蓋LOGIN_REDIRECT_URL,以便我的用戶在登錄時登錄我要登錄的頁面。更改django-allauth render_authentication_error行爲

但是。當用戶打開Facebook登錄對話框,然後在沒有登錄的情況下關閉它,authentication_error.html模板被allauth.socialaccount.helpers.render_authentication_error渲染,這不是我想要的行爲。我希望用戶只需重定向到登錄頁面。

是的,我知道我可以簡單地將模板放在我的TEMPLATE_DIRS中,但是這個url不會相同。

我得出結論我需要一個中間件攔截對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 

但我不確定我的解決方案的效率,也不知道pythonesquitude(我認爲是這個詞)。除了使用中間件或信號之外,還有什麼可以改變默認的django-allauth行爲嗎?

謝謝!

回答

0

我決定用一箇中間件和重定向到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("/") 
0

是的,我知道我可以簡單地通過將模板放在我的TEMPLATE_DIRS中來覆蓋模板,但是這個url不會相同。

覆蓋模板不會更改URL。在您覆蓋的模板中,您可以對任何您喜歡的網址執行client-side redirect

+0

我的意思的URL做的是URL不會是一樣的根我想在登錄錯誤時重定向的網址。無論如何,我選擇了簡單地使用中間件,並將GET請求重定向到/ accounts/*以根URL – 2015-03-11 21:05:17

+0

很酷,很高興您找到了解決方案。 – 2015-03-11 21:06:29