2017-07-26 17 views
2

Django初學者在這裏。區分定製修飾器中的未認證用戶

我一直在使用內置的login_required裝飾。我想覆蓋某些推薦網址與特定格式匹配的用戶(例如,所有用戶始發於/buy_and_sell/)。

我的目的是向這些用戶顯示一個特殊的登錄頁面,並向其他人顯示一個通用登錄頁面。

我一直在尋找寫定製修飾器的各種例子(例如here,here,herehere)。但我覺得初學者很難掌握這些定義。有人能給我一個外行人的理解(最好是說明性的例子)我怎樣才能解決我的問題?

回答

2

Django中包含了user_passes_test修飾器。您不必製作自己的修飾器。

from django.contrib.auth.decorators import user_passes_test 

def check_special_user(user): 
    return user.filter(is_special=True) 

# if not the special user it will redirect to another login url , otherwise process the view 
@user_passes_test(check_special_user,login_url='/login/') 
def my_view(request): 
    pass 
    ... 

需要,要求在裝飾

要做到在您的項目或應用程序,使user_passes_test的克隆版本,並變更爲遵循,

def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): 
    """ 
    Decorator for views that checks that the user passes the given test, 
    redirecting to the log-in page if necessary. The test should be a callable 
    that takes the user object and returns True if the user passes. 
    """ 

    def decorator(view_func): 
     @wraps(view_func, assigned=available_attrs(view_func)) 
     def _wrapped_view(request, *args, **kwargs): 
      if test_func(request.user): # change this line to request instead of request.user 
       return view_func(request, *args, **kwargs) 
      path = request.build_absolute_uri() 
      resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) 
      # If the login url is the same scheme and net location then just 
      # use the path as the "next" url. 
      login_scheme, login_netloc = urlparse(resolved_login_url)[:2] 
      current_scheme, current_netloc = urlparse(path)[:2] 
      if ((not login_scheme or login_scheme == current_scheme) and 
        (not login_netloc or login_netloc == current_netloc)): 
       path = request.get_full_path() 
      from django.contrib.auth.views import redirect_to_login 
      return redirect_to_login(
       path, resolved_login_url, redirect_field_name) 
     return _wrapped_view 
    return decorator 

變化test_func(請求.user)到test_func(request),你將在你的裝飾器函數中獲得整個請求的 。

編輯:在url.py,

url (
    r'^your-url$', 
    user_passes_test(check_special_user, login_url='/login/')(
     my_view 
    ), 
    name='my_view' 
) 
+0

問:我將如何得到'check_special_user'轉診網址是什麼?我沒有'請求'那裏。 – Sophia111

+0

無法在user_passes_test方法裝飾器中使用請求。你究竟想要做什麼? – Aniket

+0

就像我在我的問題中提到的那樣,我試圖向**應用程序中的某些url發起的** unauth用戶**(例如'/ buy_and_sell /')顯示特殊的登錄頁面。所有其他非法用戶將被顯示爲通用登錄頁面。我需要查看'request.META.get('HTTP_REFERER')'的內容。 – Sophia111

1

這裏最好的答案,瞭解蟒蛇裝飾:How to make a chain of function decorators?

您可以使用參數login_requiredlogin_url

@login_required(login_url='some_url) 

另一種方式是t o創建一個定製的裝飾,一個例子來自documentation of Django

from django.contrib.auth.decorators import user_passes_test 

def email_check(user): 
    return user.email.endswith('@example.com') 

@user_passes_test(email_check) 
def my_view(request): 
    ... 
+0

你有沒有看到我的答案downvote的任何理由? – Aniket

+1

反正我給你+1的答案。 – Aniket