首页 > 解决方案 > NoReverseMatch at / Reverse for 'course_detail' 没有找到参数 '('',)'。尝试了 1 种模式:['course/(?P[-a-zA-Z0-9_]+)/$']

问题描述

我正在尝试制作一个具有学习区的网站,以便教师可以上传课程供用户查看。我正在尝试将 url 添加到主页以链接到课程概述页面,当我尝试添加 url 时,我不断收到 NoReverseMatch 错误。

这是 urls.py 文件

from django.urls import path
from . import views

urlpatterns = [
    path('content/order/', views.ContentOrderView.as_view(), name='content_order'),
    path('subject/<slug:subject>/', views.CourseListView.as_view(), name='course_list_subject'),
    path('<slug:slug>/', views.CourseDetailView.as_view(), name='course_detail'),
]

视图.py

class CourseDetailView(DetailView):
    model = models.Course
    template_name = 'courses/course/detail.html'


class CourseListView(TemplateResponseMixin, View):
    model = models.Course
    template_name = 'courses/course/list.html'

def get(self, request, subject=None):
    subjects = models.Subject.objects.annotate(total_courses=Count('courses'))
    courses = models.Course.objects.annotate(total_modules=Count('modules'))
    if subject:
        subject = get_object_or_404(models.Subject, slug=subject)
        courses = courses.filter(subject=subject)
    return self.render_to_response({'subjects': subjects, 'subject': subject, 'courses': courses})

模板

<div class="module">
    {% for course in courses %}
        {% with subject=course.subject %}
            <h3>
                <a href="{% url 'course_detail' course.slug %}">
                    {{ course.title }}
                </a>
            </h3>
            <p>
                <a href="{% url 'course_list_subject' subject.slug %}">{{
                subject }}</a>.
                {{ course.total_modules }} modules.
                Instructor: {{ course.owner.get_full_name }}
            </p>
        {% endwith %}
    {% endfor %}

标签: pythondjango

解决方案


推荐阅读