【问题标题】:why i am not able to view with classbased (list view )but for function based view it is working fine?为什么我无法使用基于类的视图(列表视图)但对于基于函数的视图它工作正常?
【发布时间】:2018-05-20 14:15:27
【问题描述】:

我的问题:为什么我无法使用基于类的列表视图查看仅搜索 ayan rand 的书?

这是我的基于函数的商店列表视图,我正在检索我的所有书籍对象并以 HTML 呈现,它工作正常。

但使用基于类的视图“SearchBookDetail”我无法获得指定的书籍详细信息。

Views.py:

from django.shortcuts import render, get_object_or_404
from django.http import  HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView

def store_listView(request,):
      queryset=Book.objects.all()

      context={
           "objects_list":queryset
      }
      return render(request,'bookstores/store.html',context)

class SearchBookDetail(ListView):
    template_name = "bookstores/store.html"
    queryset = Book.objects.filter(author__icontains='Ayan Rand')
    print("Ayan Rand query set", queryset)

网址.py:

 from django.conf.urls import url
 from django.contrib import admin
 from django.views.generic import TemplateView
 from store.views import (Home,ContactView,LoginView,
                     store_listView,
                     SearchBookDetail,
                     book_createview,
                     QuoteslistView,
                    AyanRandBookDetail,
                     quotesFunctionView)

 urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^$',Home.as_view()),
   url(r'^contact/$',ContactView.as_view()),
   url(r'^login/$',LoginView.as_view()),
   url(r'^store/$',store_listView),
   url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
   url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
   url(r'^quotes/$',quotesFunctionView)]

store.html:

 {% extends "home.html" %}
 {% block head_title %}Store || {{ block.super }} {% endblock head_title %}
 {% block content %}
 <head>
   <meta charset="UTF-8">
   <title>Store</title>
 </head>

 <h6>Books available</h6>
 <ul>
   {% for obj in objects_list %}
   <li>{{obj}}<br>
    {{obj.book_image}} <br>
    {{obj.description}} <br>
    {{obj.author}}<br>
    {{obj.genre}}<br>
    {{obj.price}}<br>
    </li>

   {% endfor %}
</ul>


{% endblock content %}

【问题讨论】:

  • 你没有告诉我们什么是错的。会发生什么,这与您的预期有何不同?
  • 我可以使用这个 -"127.0.0.1:8000/store" 查看所有书籍对象,但是当我使用 "127.0.0.1:8000/store/SearchBookDetail" 时,我无法查看任何内容。虽然我看不到数据
  • 模板包含什么?
  • store.html:{% extends "home.html" %} {% block head_title %}Store || {{ block.super }} {% endblock head_title %} {% block content %} Store
    可用书籍
      {% for obj in objects_list %}
    • {{obj}}
      {{obj.book_image}}
      {{obj.description}}
      {{obj.author }}
      {{obj.genre}}
      {{obj.price}}
    • {% endfor %}
    {% endblock 内容 %}
  • 你应该把它作为问题的编辑。

标签: django django-templates django-views


【解决方案1】:

ListView 将其数据作为object_list 发送到模板,而不是objects_list

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2014-02-16
    • 2023-03-06
    • 2019-02-07
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多