首页 > 解决方案 > Django 2.1.2:通用详细视图 SchoolDetailView 必须使用 URLconf 中的对象 pk 或 slug 调用

问题描述

我是 django 的新手,不明白什么是 pk 或 slug。到底是怎么回事?

模型.py:

class School(models.Model):
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)

    def __str__(self):
        return self.name

模板页面:

<a class="navbar-brand" href="{% url 'basic_app:list'%}">Schools</a>

网址.py:

path('',views.SchoolDetailView.as_view(),name='list'),

视图.py:

class SchoolDetailView(DetailView):
    context_object_name = 'school_detail'
    model = models.School
    template_name = 'basic_app/school_detail.html'

标签: pythondjango

解决方案


详细视图用于获取特定对象的详细信息。为了做到这一点,您必须在您的网址中传递 pk 。

urlpatterns = [
path('<int:pk>/', SchoolDetailView.as_view(), name='school-detail'),

]

如果要显示对象列表,请使用 ListView


推荐阅读