使用get_context_data从URL获取数据来创建详细信息视图

时间:2019-02-05 18:28:58

标签: python django python-3.x

我能够从所选的title对象中将字符串值book推送到url,以显示带有以下编辑的详细信息视图:

修复了丢失的%}标签,并添加了丢失的app_name ='books'将{% url 'book_detail' book.title修复为{% url 'books:book_detail" book.title %}

views.py

class IndexView(TemplateView):
    template_name = 'app/index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['book_data'] = Book.objects.all()
        context['books_by_john'] = Books.objects.filter(author = 'John')

        return context

urls.py

app_name = 'books'
urlpatterns = [
    path('login/', views.LoginView.as_view(), name='login'),
    path('login/index/', views.IndexView.as_view(), name='index'),
    path('login/index/<str:key>', views.BookView.as_view(), name ='book_detail')

index.html

<ul>
    {% for book in book_data %}
    <li><a href="{% url 'books:book_detail' book.title %}"> {{book.title}} - {{book.name}} - {{book.author}}</a> </li>
    {% endfor %}
</ul>

现在我将如何使用此url中的值在详细视图中仅显示特定书籍的数据?所以它会做这样的事情

views.py

class BookView(TemplateView):
    template_name = 'app/book_info.html'

    def get_context_data(self, **kwargs):
        context = super(BookView, self).get_context_data(**kwargs)
        context['book_description'] = Book.objects.filter(title=<title from url>)
        return context

EDIT2:最终,我将需要多个数据集来从IndexView中提取数据,如果这样的话,我应该使用listview吗?以及如何在列表视图中使用多个查询集

2 个答案:

答案 0 :(得分:3)

您的模板标签格式错误;您缺少结尾%}。因此,它根本不会被解析为标签。

应该是:

<li><a href="{% url 'book_detail' book.title %}"> {{book.title}} - {{book.name}} - {{book.author}}</a> </li>

对于其他问题,应使用更合适的视图进行子类化。在您的情况下,DetailView可以完全满足您的需求。 (并且您的索引视图应基于ListView,这将完全不需要您的get_context_data方法。)

答案 1 :(得分:0)

我知道这可能不是执行此操作的正确方法(通过使用TemplateViews代替ListView和DetailViews)。但是由于我最终将要为IndexView使用来自多个模型的多个数据集,所以我一直坚持使用TemplateView。如果有人可以解释为什么这是一个坏主意,我将不胜感激

但是我通过在我的网址路径中添加slug而不是str来解决了这个问题

path('login/index/<slug:title>', views.BookView.as_view(), name ='book_detail')

像这样将context['book_description'] = Book.objects.filter(title = self.kwargs['title'])添加到我的BookView

class BookView(TemplateView):
    template_name = 'app/book_info.html'

    def get_context_data(self, **kwargs):
        context = super(BookView, self).get_context_data(**kwargs)
        context['book_description'] = Book.objects.filter(title = self.kwargs['title'])
    return context

我能够创建数据集,以通过book_detail.html模板中url中的标题过滤Book模型

 {% for x in book_description %}

    <li>{{ x.summary }}</li>
 {% endfor %}