Skip to main content
 首页 » 编程设计

python之Django URL conf conf 重定向到错误的 View

2025年05月04日39zhenyulu

为大学生编写一个应用程序——显示一个系列表,你点击一个,然后它会显示该系的类(class),点击一个,然后显示教授该类(class)的教授。

URL conf 有问题——我的应用程序不断将我重定向到错误的 View 。

所以我有 3 个模型

class Department(models.Model): 
    subject         = models.CharField(max_length = 25) 
    pub_date        = models.DateTimeField(auto_now_add = True) 
 
    def __unicode__(self): 
        return self.subject 
 
class Course(models.Model): 
    department      = models.ForeignKey(Department) 
    course_number   = models.CharField(max_length = 50) 
    course_name     = models.CharField(max_length = 100, blank = True, null = True) 
    c_pub_date      = models.DateTimeField(auto_now_add = True) 
 
    def __unicode__(self): 
        return self.course_number 
 
class Professor(models.Model): 
    course          = models.ForeignKey(Course) 
    prof_name       = models.CharField(max_length = 50) 
    p_pub_date      = models.DateTimeField(auto_now_add = True) 
 
    def __unicode__(self): 
        return self.prof_name 

然后我的应用程序 URL conf 根据 URL 转到 View 、类(class)和教授

urlpatterns = patterns('qanda.views', 
    url(r'^$', 'index'), 
    url(r'(?P<department_id>\d+)/$', 'courses'), 
    url(r'(?P<department_id>\d+)/(?P<course_id>\d+)/$', 'professors'), 
) 

所以当我访问 url mysite.com 时,它会列出数据库中的所有部门。然后单击一个部门(即数学),它将带我到 mysite.com/1 上的类(class) View ,它显示了该部门的所有类(class)。然后单击一门类(class)应将我带到教授 View mysite.com/1/1,其中显示了教授该类(class)的所有教授。

但是,当我进入类(class) View 并单击类(class)以进入教授 View 时,即使 URL 显示为 mysite.com/1/2,它实际上会将我重定向回 mysite.com/2,采取course_id(在本例中为 2)并将其误认为是 departmment_id,并将我重定向到类(class) View 。

例如,数学 101 course_id = 1。数学 102 course_id = 2。对于数学 101,有 2 位教授。 A教授professor_id = 1,B教授professor_id = 2。

因此,当单击 Math 101 时,URL 将为 mysite.com/1。之后点击 Professor B 时,URL 将为 mysite.com/1/2。然而,现在当点击教授 B 时,URl 显示 mysite.com/1/2,但将我带到 mysite.com/2。

知道为什么会这样吗?

请您参考如下方法:

你的问题是你的正则表达式太模糊了..你错过了 ^ 所以你的第一个 URL 在你的第二个有机会之前匹配。

(\d+)/$ 会匹配 /3/, foo/3/, foo/bar/baz/3

它与尾部斜杠无关。这是一个标准的 Django URL 模式。 /$

url(r'^$', 'index'), 
url(r'(?P<department_id>\d+)/$', 'courses'), 
#   ^^^ needs ^ 
url(r'(?P<department_id>\d+)/(?P<course_id>\d+)/$', 'professors'),