在编写视图时,使用 @login_required 装饰器显然是一个好习惯——如果不是强制性的话。
但是 - 只检查验证用户
from django.contrib.auth.models import User
我想要完成的是还要检查用户是否作为用户配置文件存在。例如,在我的应用程序中,我有一些用户配置文件。当然,它们都有与之相关的 User 对象。但我也有其他没有用户配置文件的用户。这样的用户是我的管理员用户。我想确保请求来自拥有 UserProfiles(并且经过身份验证)的用户。
有没有办法改变装饰器来支持它?目前我只是编写了自己的代码来做到这一点:
def user_login(request):
context = context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
try:
user = authenticate(username=username, password=password)
user_profile = user.userprofile
except (ObjectDoesNotExist,AttributeError) as e:
# username and password only prompted for debug purposes.
error_msg = "Invalid login details: {0}, {1}".format(username, password)
print (error_msg)
# print (request)
# return HttpResponse("Invalid login details supplied.")
return render(request, 'bz/login.html', {'error_msg': error_msg})
if user and user_profile:
if user.is_active:
login(request,user)
# return HttpResponse("You're now logged in as " + username)
# return render(request, 'bz/index.html', {})
return render(request, 'bz/index.html', {'userprofile': user_profile})
# return HttpResponseRedirect('bz/login.html')
else:
error_msg = "Your account is disabled"
print (error_msg)
return render(request, 'bz/login.html', {'error_msg': error_msg})
# return HttpResponse(error_msg)
else:
error_msg = "Invalid login details: {0}, {1}".format(username, password)
print (error_msg)
return render(request, 'bz/login.html', {'error_msg': error_msg})
# return HttpResponse("Invalid login details supplied.")
else:
if request.user.is_authenticated():
return render(request, 'bz/index.html', {})
else:
return render(request, 'bz/login.html', {})
您的意见将不胜感激。谢谢你。