我注意到django如何处理我的url模式有一个奇怪的行为。用户应登录,然后重定向到其配置文件页。我还可以让用户编辑他们的个人资料。
以下是我的某个应用程序的URL模式:

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

这是一个叫学生的应用程序。如果用户转到/student/profile,他们应该获得profile视图。如果他们转到/student/editprofile,他们应该得到editprofile视图我设置了一个名为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时,profile页面是加载的内容,这是打印的内容:
Going to <function profile at 0x02FCA370>
Going to <function editprofile at 0x02FCA3F0>
Going to <function view_profile at 0x02FCA4F0>

view_profile是一个完全不同的应用程序中的函数。

最佳答案

这两种模式:

(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)。

10-06 05:17
查看更多