我指定了一个列出学生的URL和一个显示学生详细信息的URL,但是该学生详细信息的URL似乎不起作用。
ursl.py看起来像这样:
urlpatterns = [
path('', views.SchoolListView.as_view(), name='list'),
path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
path('create/', views.SchoolCreateView.as_view(),name='create'),
path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
path('delete/<int:pk>/',views.SchoolDeleteView.as_view(),name='delete'),
path('students', views.StudentListView.as_view(), name='student_list'),
path('students/<int:pk>/',views.StudentDetailView.as_view(),name='student_details'),
]
但是当我单击实际的学生时,它并不会带我到basic_app / students / 1(例如),而是带我到basic_app / 1
此外,当我手动输入/ basic_app / students / 1时,我也会看到一条错误消息:
NoReverseMatch at /basic_app/students/1/
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1
pattern(s) tried: ['basic_app/update/(?P<pk>[0-9]+)/$']
我的观点:
class StudentListView(ListView):
context_object_name = 'students'
model = models.Student
class StudentDetailView(DetailView):
context_object_name = 'student_details'
model = models.Student
template_name = 'basic_app/student_detail.html'
模型:
class Student(models.Model):
name = models.CharField(max_length=150)
age = models.PositiveIntegerField()
school = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("basic_app:student_details",kwargs={'pk':self.pk})
student_details.html模板:
{% extends 'basic_app/basic_app_base.html' %}
{% block body_block %}
<div class="container jumbotron">
<h2>Student Details:</h2>
<p>Name: {{student_details.name}}</p>
<p>Principal: {{student_details.age}}</p>
<p>Location: {{student_details.school}}</p>
<!-- <div class="container">
<a class="btn btn-primary" href="{% url 'basic_app:update' pk=school_details.pk %}">Update</a>
<a class="btn btn-danger" href="{% url 'basic_app:delete' pk=school_details.pk %}">Delete</a>
<a href="{% url 'basic_app:list' %}">Cancel</a>
</div> -->
{% endblock %}
我做错了什么?`
答案 0 :(得分:0)
student_details.html中被注释掉的部分可能会产生错误。删除该部分,它应该可以工作:
{% extends 'basic_app/basic_app_base.html' %}
{% block body_block %}
<div class="container jumbotron">
<h2>Student Details:</h2>
<p>Name: {{student_details.name}}</p>
<p>Principal: {{student_details.age}}</p>
<p>Location: {{student_details.school}}</p>
{% endblock %}