2014-01-11 94 views

回答

0

我會創建第三個觀點,即只檢查用戶的狀態,然後調用正確的觀點:

import A.views 
import B.views 

def combined_index(request, *args, **kwargs): 
    """Call A.views.index if user is authenticated, otherwise B.views.index.""" 
    if request.user.is_authenticated(): 
     return A.views.index(request, *args, **kwargs) 
    else: 
     return B.views.index(request, *args, **kwargs) 

如果你想基於B是否在INSTALLED_APPS這個可選的,根本就:

import A.views 

from django.conf import settings 

if 'B' in settings.INSTALLED_APPS: 
    import B.views 
    def combined_index(...): 
     # as above 
else: 
    combined_index = A.views.index 
1

幾種方法:

  • 使用同樣的觀點,並檢查用戶是否在視開始驗證過。
  • 創建虛擬視圖。在這個虛擬視圖之前創建視圖裝飾器。在裝飾器中檢查用戶是否已通過驗證,然後從裝飾器返回兩個視圖中的一個
  • 使用相同視圖,只需向視圖模板添加一個附加參數即可。併爲不同的用戶呈現不同的模板。
+0

嗨@Odif我不能使用相同的視圖/應用程序。應用程序'A'是獨立的,應用程序'B'就像一個附加組件,只需在'settings.py'中刪除它就可以刪除,而不會破壞任何功能。有沒有什麼辦法可以重定向到應用程序的視圖,而無需聲明任何命名空間? – Sourabh

+0

那麼如果是這種情況,那麼你可以註冊一個更多的視圖到相同的地址。在settings.py/urls.py中包含其他項目/視圖之前聲明它,並從那裏使用你的魔法。你可以在那裏使用第二種方法。創建虛擬視圖,如果第二個應用程序未註冊(例如導入失敗),則返回第一個應用程序的視圖。如果不是,那麼...遵循其他邏輯是必要的 –

0

使用相同的視圖,並檢查用戶是否在視圖的開始進行身份驗證。

我認爲這是一個天生的解決方案。

def login_view(request): 
result = get_response_code('success') 

# POST means user is logging in 
if request.method == 'POST': 
    username = request.POST.get('username', '') 
    password = request.POST.get('password', '') 
    next = request.GET.get('next', '') 
    user = auth.authenticate(username=username, password=password) 
    if user and user.is_active: 
     logger.info('Authenticate success for user ' + username) 
     # Correct password, and the user is marked "active" 
     auth.login(request, user) 
     if next: 
      return redirect(next) 
     else: 
      return redirect('/admin') 
    else: 
     logger.info('Authenticate failed for user ' + username) 
     result = get_response_code('auth_failed_invalid_username_or_password') 
# Just show the login page 
return render_to_response('account/login.html', 
          locals(), 
          context_instance=RequestContext(request)) 
相關問題