Django - 查看,网址奇怪

问题描述:

我注意到一个奇怪的行为与Django如何处理我的url模式。用户应该登录,然后重定向到他们的个人资料页面。我也有能力让用户编辑他们的个人资料。Django - 查看,网址奇怪

这里是我的我的应用程序的一个URL模式:

urlpatterns=patterns('student.views', 
    (r'profile/$', login_required(profile,'student')), 
    (r'editprofile/$', login_required(editprofile,'student')), 
) 

这是被称为学生的应用程序。如果用户转到/ student/profile,他们应该得到配置文件视图。如果他们去/学生/ 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 

不管怎么说,奇怪的事情是,当我访问/学生/ profile文件,即使我得到正确的页面,login_required打印以下内容:

Going to <function profile at 0x03015DF0> 
Going to <function editprofile at 0x03015BB0> 

为什么要同时打印?为什么它试图访问这两个?

更加古怪,当我试图访问/学生/ editprofile,个人资料页是什么样的负载,这是集团的印刷什么:

Going to <function profile at 0x02FCA370> 
Going to <function editprofile at 0x02FCA3F0> 
Going to <function view_profile at 0x02FCA4F0> 

view_profile是在一个完全不同的应用程序的功能。

+3

关于decorators.login_required()和decorators.permission_required()是什么让人无法忍受? – hop 2011-01-24 19:11:20

这两种模式:

(r'profile/$', login_required(profile,'student')), 
(r'editprofile/$', login_required(editprofile,'student')), 

都匹配http://your-site/student/editprofile

尝试:

(r'^profile/$', login_required(profile,'student')), 
(r'^editprofile/$', login_required(editprofile,'student')), 

Django使用谁的模式首先匹配(see number 3 here)的观点。

+0

这是个问题。我认为,因为这urls.py被包含在另一个urls.py,我不会在前面使用'^',但事实证明我需要。谢谢! – JPC 2011-01-24 21:31:04

您的login_required看起来像是一个Python装饰器。任何你需要在你的urls.py中拥有它的理由?

我认为print 'Going to '+str(view)线正在被评估,当urlpatterns被读取,以确定要执行的视图。它看起来很奇怪,但我认为它不会伤害你。

线print 'Going to '+str(view)就不会在每次视图被击中时执行,只有当URL模式进行评估(我认为)。在new_view的代码是将对于某些执行作为视图的一部分的唯一代码。

+0

也许我可以用它作为装饰。但即使如此...确实,你对new_view的执行是正确的,但是为什么当我尝试编辑配置文件时会加载错误的视图 – JPC 2011-01-24 21:26:19

不知道为什么你不能使用标准@login_required装饰 - 似乎你的版本实际上提供的功能,因为它总是重定向到\,而不是实际的登录视图。

在任何情况下,为什么既被打印的原因是因为所述print语句是在装饰的顶层,因此当URL配置是评价被执行。如果将它放在内部new_view函数中,它只会在实际调用时执行,并且应只打印相关的视图名称。

+0

您对打印语句是正确的,但为什么错误的视图仍然返回editprofile – JPC 2011-01-24 21:26:56