Django:NoReverseMatch at / courses / 2 /

时间:2016-09-30 07:29:17

标签: django

获取此错误:

Reverse for 'step' with arguments '()' and keyword arguments '{'course_pk': 2, 'step_pk': ''}' not found. 1 pattern(s) tried: ['courses/(?P<course_pk>\\d+)/(?P<step_pk>\\d+)/']

<强烈> /urls.py

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

/courses/urls.py

...
url(r'(?P<course_pk>\d+)/(?P<step_pk>\d+)/$', views.step_detail, name='step'),
...

模板渲染期间出错: 生成错误的html行是:

...
 <a href=" {% url 'courses:step' course_pk=step.course.pk step_pk=step_pk %} ">{{ step.title }}</a> 
...

课程/ models.py

class Course(models.Model):
    created_at = models.DateTimeField(auto_now_add=True) 
    title = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self):
        return self.title


class Step(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    content = models.TextField(blank=True, default='')
    order = models.IntegerField(default=0)
    course = models.ForeignKey(Course)

    class Meta:
        ordering = ['order', ]

    def __str__(self):
        return self.title

课程/ views.py

def course_detail(request, pk):
    # course = Course.objects.get(pk=pk)
    course =  get_object_or_404(Course, pk=pk) 
    return render(request, "courses/course_detail.html", {"course": course})


def step_detail(request, course_pk, step_pk):
    step = get_object_or_404(Step, course_id=course_pk, pk=step_pk)
    return render(request, "courses/step_detail.html", {"step": step})

我似乎无法理解问题出在哪里,因为我目前刚刚接触Django。很多帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

你需要

{% url 'courses:step' course_pk=step.course.pk step_pk=step.pk %}

step.pk而不是您的上下文中不存在的step_pk

答案 1 :(得分:0)

在第

    <a href=" {% url 'courses:step' course_pk=step.course.pk step_pk=step_pk %} ">

这里step_pk = step_pk不起作用。未定义Step_pk,因为您未在此行的def course_detail中返回有关step_pk的任何信息:

      return render(request, "courses/course_detail.html", {"course": course})

在return内部传递步骤并使用step_pk = step.pk

请检查一下。感谢。