基于类的DetailView中的键错误

时间:2018-05-20 10:32:07

标签: django django-class-based-views keyerror

之前我曾经遇到过这个问题,但我一直都能解决这个问题。这次我不能。它刚回来了:

“溪流的关键错误/ sport_slug 'PK' “

视图中第34行的错误,我在下面重点介绍:

Views.py:

class StreamSport(ListView):
    template_name = "stream/stream-index.html"
    context_object_name = 'stream_list'

    def get_queryset(self):
        self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug'])
        *self.pk = get_object_or_404(Video, pk=self.kwargs['pk'])*
        return Video.objects.filter(sport=self.sport, pk=self.pk)

URLs.py:

app_name = 'streams'

urlpatterns = [
    path('', StreamIndex.as_view(), name='stream-index'),
    path('<slug:sport_slug>/', StreamSport.as_view(), name='stream-sport'),
    path('<slug:sport_slug>/<int:pk>/', StreamDetail.as_view(), name='detail'),

流的index.html:

<a href="{% url 'streams:detail' video.sport.sport_slug video.pk %}"

编辑:作为Lemayzeur,我感到困惑。关键错误是由尝试修复另一个错误引起的。相反,当我向后移动时,我以为我取得了进步。原始错误,以及我现在回到的错误是“反向'带有参数的'详细信息'错误。

为了澄清,我要做的是构建一个ListView,列出模型中的所有视频,然后将每个视频链接到自己的详细信息页面。它的DetailView本身给了我一些问题:

class StreamDetail(DetailView):
    model = Video
    template_name = 'stream/detail.html'

    def get_queryset(self):
        self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug'])
        self.pk = Video.objects.filter(pk=self.kwargs['pk'])
        return Video.objects.filter(sport=self.sport, pk=self.pk)

这是它给我的错误:

Reverse for 'detail' with arguments '(2,)' not found. 1 pattern(s) tried: ['stream\\/(?P<sport_slug>[-a-zA-Z0-9_]+)\\/(?P<pk>[0-9]+)\\/$']

回溯本身非常无用,它只是指向基本文件中的bootstrapcdn。

流的index.html:

{% for video in stream_list %}
  <div class="card" style="width: 20rem;margin-left: 2rem;">
            <img class="card-img-top" src="{{video.headline_image.url}}" alt="Card image cap" style="width: 20rem;">
            <div class="card-body" style="width: 18rem;">
              <h5 class="card-title"><a href="{% url 'streams:detail' video.id %}">{{video.name}}</a></h5>
              <p class="card-text" style="width: 18rem;">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
              <a href="{% url 'streams:detail' video.sport.sport_slug video.pk %}" class="btn btn-success">Watch Now</a>
              <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
            </div>
        </div>
{% endfor %}

2 个答案:

答案 0 :(得分:1)

当您在完整代码段中显示时,在您的模板中,您只是将<a href="{% url 'streams:detail' video.sport.sport_slug video.id %}"> 传递给url标记,而详细网址则需要id和slug。确保你通过它们:

{{1}}

答案 1 :(得分:0)

错误不在您发布的网址中: 检查此行

而不是

<h5 class="card-title"><a href="{% url 'streams:detail' video.id %}">{{video.name}}</a></h5>

应该是

<h5 class="card-title"><a href="{% url 'streams:detail' video.sport.sport_slug video.pk %}">{{video.name}}</a></h5>