Mfreeman
Mfreeman

Reputation: 3968

In a template, how to create if statement when model.value == "str"

In my detail.html template i'm trying to create 2 separate views depending if the books genre is either fiction or nonfiction. How do i create the if statement for this in this scenario

{% if genre == Fiction %}
    {% for x in book %}

    <h1>{{x.title}}: </h1>
    {% endfor %}

{% else %}

<h1> This is the other sections</h1>
{% endif %}

My book model has a value of "genre" that takes a string. How to i access this in the "if" statement in my templates?

EDIT:

views.py

    class BookDetailView(TemplateView):                                       
        template_name = 'app/detail.html'                                

        def get_context_data(self, **kwargs):                                 
            context = super(BookDetailView, self).get_context_data(**kwargs)  
            context['book'] = Book.objects.filter(key=self.kwargs['key'])

I know I should be using detailviews to do this but this is a snippet of a much larger project, and went with template views instead

This is to show detail of a book, but want the page to look different depending on genre

Upvotes: 0

Views: 144

Answers (2)

Swetank Subham
Swetank Subham

Reputation: 169

For now I am assuming that you have a models.py somewhat as:

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)

and views.py as:

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)

Now in template (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 %}

Upvotes: 2

gdef_
gdef_

Reputation: 1936

Book.objects.filter(... will return a queryset, use Book.objects.get(... to get a specific one.

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

Then access it directly and no for-loop is needed.

{% if book.genre == "fiction" %}
    <h1>{{book.title}}: </h1>
{% else %}
    <h1> This is the other sections</h1>
{% endif %}

Upvotes: 1

Related Questions