在我的detail.html模板中,我尝试根据图书类型是小说还是非小说来创建2个单独的视图。在这种情况下,如何为此创建if语句
array_count_values()
我的书本模型的“类型”值带有字符串。如何在模板的“ if”语句中访问此内容?
编辑:
views.py
$array = explode(', ' , 'John, Ali, Ali, Mark, Susan, Susan, Susan, Ali, Julie, John');
$count = array_count_values( $array );
我知道我应该使用detailviews来做到这一点,但这是一个更大项目的一小段,而是使用模板视图
这是为了显示一本书的详细信息,但希望页面根据体裁而有所不同
答案 0 :(得分:1)
Book.objects.filter(...
将返回一个查询集,使用Book.objects.get(...
获得一个特定的查询集。
def get_context_data(self, **kwargs):
context = super(BookDetailView, self).get_context_data(**kwargs)
context['book'] = Book.objects.get(key=self.kwargs['key'])
return context
然后直接访问它,不需要for循环。
{% if book.genre == "fiction" %}
<h1>{{book.title}}: </h1>
{% else %}
<h1> This is the other sections</h1>
{% endif %}
答案 1 :(得分:1)
目前,我假设您有一个models.py,如下所示:
from django.db import models
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=True)
author = models.CharField(max_length=255, blank=True)
genre = models.CharField(max_length=255, blank=True)
和views.py为:
from django.shortcuts import render
from django.views import View
from .models import Book
class Books(View):
def get(self, request):
all_books = Book.objects.all() # assuming you are fetching all the books
context = {'books': all_books}
return render(request, 'Your_Template.html', context=context)
现在在模板(Your_Template.html)中:
{% for book in books %}
{% ifequal book.genre|stringformat:'s' 'fiction' %}
{{ book.name }} is of genre 'fiction'.
{% else %}
{{ book.name }} is of genre '{{ book.genre }}'.
{% endifequal %}
{% endfor %}