django,detailview 页面不显示

django, detailview page not showing

单击 link 时无法显示详细信息视图。 “找不到页面 (404)” 一切正常,直到我点击卡片名称,然后将我重定向到 127.0.0.1:8000/Electric/1/ 并给出错误“找不到页面(404)”

查看

class ElectricDetailView(DetailView):
    model = Product
    template_name = "Electric.html"
    queryset = Product.objects.all()

    def get_object(self, queryset=None):
        id_ = self.kwargs.get("id")
        return get_object_or_404(Product, id=id_)

class ElectricView(ListView):
    model = Product
    queryset = Product.objects.filter(type__name='Electric')
    context_object_name = 'product'
    template_name = 'Electric.html'

url.py 路径


    path('Electric/', ElectricView.as_view(), name='electric'),
    path('Electric/<int:pk>', ElectricDetailView.as_view(), name='Detailelec'),

在html文件中

   <section class="text-center mb-4">
        <div class="row wow fadeIn">
         {% for p in object_list %}
          <div class="col-lg-3 col-md-6 mb-4">
            <div class="card">
              <div class="view overlay">
                <img src="{{ p.carimg }}" class="card-img-top" alt="">
                <a>
                  <div class="mask rgba-white-slight">
                  </div>
                </a>
              </div>            
             <div class="card-body text-center">
                <!--Category & Title-->
                <a href="/Electric/{{ p.id }}/" class="grey-text">
                  <h5>{{ p.name }}</h5>
                </a>
                <h4>
                  <strong>
                    {{ p.year_released }} AD
                  </strong>
                </h4>
                <h4 class="font-weight-bold blue-text">
                  <strong>{{ p.price }} €</strong>
                </h4>
              </div>
             </div>
          </div>

           {% endfor %}
        </div>
      </section>

在详细视图的 urls.py 文件中添加尾部斜杠:

path('Electric/<int:pk>/', ElectricDetailView.as_view(), name='Detailelec'),

此外,您可以跳过定义以下部分:

    ...
    queryset = Product.objects.all()

def get_object(self, queryset=None):
    id_ = self.kwargs.get("id")
    return get_object_or_404(Product, id=id_)