Django的DetailView

时间:2018-06-24 09:14:37

标签: python django

我是Django的初学者。我有以下简单的Django模型(请参阅下文)。我的列表视图在https://localhost/simpleapp/中运行良好。但是,当我通过https:local host / simpleapp / 1尝试DetailView时,它给了我404错误。我不知道问题出在哪里,因为我已经用正则表达式^(?P \ d +)/ $定义了网址。

Model.py

class University(models.Model):
    university_name = models.CharField(max_length = 50)

    def __str__(self):
        return self.university_name

class Student(models.Model):
    last_name = models.CharField(max_length = 50)
    first_name = models.CharField(max_length = 50)
    age = models.PositiveIntegerField()
    university = models.ForeignKey(University, on_delete=True)

    def __str__(self):
        return '{} {}'.format(self.first_name, self.last_name)

Views.py

class StudentList(generic.ListView):
    model = models.Student
    context_object_name = 'student_list'
    template_name = 'simpleapp/student_list.html'


class StudentDetail(generic.DetailView):
    model = models.Student
    context_object_name = 'student_detail'
    template_name = 'simpleapp/student_detail.html'

应用文件夹中的urls.py

urlpatterns = [
    url(r'^$', views.StudentList.as_view(), name='student_list'),
    url(r'^(?P<pk>\d+)/$', views.StudentDetail.as_view(), name='student_detail'),

]

项目文件夹中的urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.Index.as_view(), name='index' ),
    url(r'^simpleapp/$', include('simpleapp.urls', namespace='simpleapp')),
]

student_detail.html

{% extends 'simpleapp/student_base.html' %}

{% block content %}

<h1> {{student_detail}}</h1>

{% endfor %}

{% endblock %}

2 个答案:

答案 0 :(得分:0)

url(r'^simpleapp/$', include('simpleapp.urls', namespace='simpleapp')),

此处Django将匹配所有以simepleapp/开头(因为以^结尾)和以url结束的URL(由于$结尾)。

/simpleapp/1与网址匹配器不匹配。

相反,请尝试将网址更改为

url(r'^simpleapp/', include('simpleapp.urls', namespace='simpleapp')),

这样,任何以simepleapp开头的网址都将被匹配

答案 1 :(得分:0)

在包含simpleapp url的模式末尾有一个$,这意味着将不再匹配。因此,基本的/ simpleapp / URL可以使用,但此后的任何操作都无效。删除该$;仅用于完整模式,不包括在内。