我有一个包含 2 个模型的应用程序,我正在尝试创建一个列表视图和一个详细信息视图。列表视图工作正常,但是当我创建详细视图时,列表视图停止工作,并提示我出现以下错误: “字段 'id' 需要一个数字,但得到了 'list'。
模型.py
from django.db import models
# Create your models here.
class schools(models.Model):
name=models.CharField(max_length=256)
principal=models.CharField(max_length=256)
def __str__(self):
return self.name
class students(models.Model):
name=models.CharField(max_length=256)
age=models.PositiveIntegerField()
school=models.ForeignKey(schools,related_name='students',on_delete=models.CASCADE)
views.py
from django.shortcuts import render
from django.views.generic import DetailView,ListView,CreateView,FormView,UpdateView
from basicapp import models,forms
from django.http import HttpResponseRedirect, HttpResponse
# Create your views here.
class SchoolListView(ListView):
model = models.schools
class SchoolDetailView(DetailView):
context_object_name='schools_detail'
model=models.schools
template_name='basicapp/schools_detail.html'
urls.py
from django.contrib import admin
from django.urls import path,re_path
from basicapp import views
urlpatterns=[
re_path(r'^(?P<pk>[-\w]+)/$',views.SchoolDetailView.as_view(),name="detail"),
path('list',views.SchoolListView.as_view(),name="list"),
path('create',views.cview.as_view(),name="create"),
path('index',views.index,name='index'),
]
和我的模板:
{% extends 'basicapp/base.html' %}
{% block body_block %}
<h1>Welcome to the List of Schools Page!</h1>
<ol>
{% for school in schools_list %}
<h2>
<li><a href="{{school.id}}"></a>{{school.name}}</li>
</h2>
{% endfor %}
</ol>
{% endblock %}
{% extends 'basicapp/base.html' %}
{% block body_block %}
<div class="jumbotron">
<h1>School Detail Page</h1>
<h2>School Details:</h2>
<p>{{ schools_detail.name }}</p>
<p>{{ schools_detail.principal }}</p>
<h3>Students:</h3>
{% for student in school_detail.students.all %}
<p>{{ student.name }} who is {{ student.age }} years old.</p>
{% endfor %}
</div>
{% endblock %}
答案 0 :(得分:0)
您的模式 Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python39\caterpillar.py", line 68, in <module>
caterpillar.forward(caterpillar_speed)
NameError: name 'caterpillar_speed' is not defined
匹配 ^(?P<pk>[-\w]+)/$
因此视图 list
被用于该网址(实际上也用于它之后的其他网址),因此您需要使模式更具体.例如 pk 将只是一个整数,所以你可以匹配它:
SchoolDetailView
更好的是,这不需要您使用 re_path(r'^(?P<pk>\d+)/$', views.SchoolDetailView.as_view(), name="detail"),
是吗?默认的 re_path
路径转换器处理得很好:
int
注意:理想情况下,类名应该在 path('<int:pk>/', views.SchoolDetailView.as_view(), name="detail"),
中,并且模型名应该是 singular 所以而不是 更好
模型的名称将是 PascalCase
schools
,而不是 它
将是 School
students
。见PEP 8 -- Style Guide for Python
Code