问题描述
|
我有几个函数需要有一个“重定向”过滤器。重定向过滤器是这样的-
1)如果用户未登录且没有会话数据,请重定向到登录页面。
2)如果用户已登录并且已经填写了该页面,请重定向到用户主页。
3)如果用户已登录并且尚未填写页面,请停留在该页面上。
4)如果用户未登录并具有会话数据,请留在页面上
我已经开始将函数转换为基于类的方法,以使其效率更高,代码更少(以前,我的视图函数非常庞大)。这是我尝试制作基于类的东西的第一步,而这就是我到目前为止所拥有的-
def redirect_filter(request):
if request.user.is_authenticated():
user = User.objects.get(email=request.user.username)
if user.get_profile().getting_started_boolean:
return redirect(\'/home/\') ## redirect to home if a logged-in user with profile filled out
else:
pass ## otherwise,stay on the current page
else
username = request.session.get(\'username\')
if not username: ## if not logged in,no session info,redirect to user login
return redirect(\'/account/login\')
else:
pass ## otherwise,stay on the current page
def getting_started_info(request,positions=[]):
location = request.session.get(\'location\')
redirect_filter(request)
if request.method == \'POST\':
form = GettingStartedForm(request.POST)
...(run the function)...
else:
form = GettingStartedForm() # inital = {\'location\': location}
return render_to_response(\'registration/getting_started_info1.html\',{\'form\':form,\'positions\': positions,},context_instance=RequestContext(request))
显然,这种观点还没有完全发挥作用。我如何将其转换为功能正常的东西?
另外,我有三个变量需要在多个ѭ1函数中重用:
user = User.objects.get(email=request.user.username)
profile = UserProfile.objects.get(user=user)
location = profile.location
我将这些变量定义放在哪里,以便可以在所有函数中重用它们,又如何称呼它们?
谢谢。
解决方法
Django实际上已经包含了login_required装饰器,使处理用户身份验证变得微不足道。只需在view.py页面顶部添加以下内容:
from django.contrib.auth.decorators import login_required
然后添加
@login_required
在任何需要登录的视图之前。用户登录后,它甚至可以将用户重定向到相应的页面。
更多信息在这里:
https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator
这将大大简化您的视图,并且可能会导致不必编写单独的类,因为剩下的都是简单的重定向。
至于变量,每个请求已经包含一个带有用户信息的request.user对象。您可以在文档中搜索“请求和响应”对象以了解更多信息。
您可以通过扩展用户模块来使用该用户对象来获取配置文件变量。在“设置”中设置AUTH_PROFILE_MODULE = \'myapp.UserProfile \',这将允许您按以下方式访问用户个人资料:
user.get_profile().location.
有关此的更多信息:
http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/