【发布时间】:2011-06-14 17:03:13
【问题描述】:
我注意到 Django 处理我的 url 模式的一种奇怪行为。用户应该登录,然后被重定向到他们的个人资料页面。我还可以让用户编辑他们的个人资料。
这是我的一个应用程序的 URL 模式:
urlpatterns=patterns('student.views',
(r'profile/$', login_required(profile,'student')),
(r'editprofile/$', login_required(editprofile,'student')),
)
这是针对名为 student 的应用程序。如果用户去 /student/profile 他们应该得到配置文件视图。如果他们去 /student/editprofile 他们应该得到 editprofile 视图。我设置了一个名为 login_required 的函数,它对用户进行一些检查。这比我仅使用注释可以处理的要复杂一些。
这里是 login_required:
def login_required(view,user_type='common'):
print 'Going to '+str(view)
def new_view(request,*args,**kwargs):
if(user_type == 'common'):
perm = ''
else:
perm = user_type+'.is_'+user_type
if not request.user.is_authenticated():
messages.error(request,'You must be logged in. Please log in.')
return HttpResponseRedirect('/')
elif request.user.is_authenticated() and user_type != 'common' and not request.user.has_perm(perm):
messages.error(request,'You must be an '+user_type+' to visit this page. Please log in.')
return HttpResponseRedirect('/')
return view(request,*args,**kwargs)
return new_view
无论如何,奇怪的是,当我访问 /student/profile 时,即使我到达了正确的页面,login_required 也会打印以下内容:
Going to <function profile at 0x03015DF0>
Going to <function editprofile at 0x03015BB0>
为什么要同时打印?为什么要同时访问两者?
更奇怪的是,当我尝试访问 /student/editprofile 时,加载的是个人资料页面,这就是打印的内容:
Going to <function profile at 0x02FCA370>
Going to <function editprofile at 0x02FCA3F0>
Going to <function view_profile at 0x02FCA4F0>
view_profile 是一个完全不同的应用程序中的函数。
【问题讨论】:
-
decorators.login_required() 和 decorators.permission_required() 有什么让人难以忍受的地方??
标签: python django django-urls