我在应用index
中有一个A
视图,在应用index
中有一个B
,两者都是网址/
。我想对经过身份验证的用户使用A.views.index
,如果用户是匿名用户,则使用B.view.index
。
我怎样才能做到这一点?也许在ProjectRoot/ProjectRoot/
中添加views.py并使用它转发到应用的视图
答案 0 :(得分:1)
有几种方法:
答案 1 :(得分: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))
答案 2 :(得分: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