Reputation: 35
I can't find out why this is not working. It always goes to {% else %} block. The text in machine_model is something like "Lidl - Food Market" or "Kaufland - Buy Here" or something other without those two words.
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django import forms
from django.urls import reverse
class MyName(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MyModel(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MySide(models.Model):
name = models.CharField(max_length=50, unique=True)
class MyMachine(models.Model):
date_delivery = models.DateTimeField(null=True)
machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT)
machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT)
machine_serial = models.CharField(max_length=15, default='0')
use_side = models.ForeignKey(MySide, on_delete=models.PROTECT)
views.py
from django.views.generic import ListView
from .models import MyMachine
class MyMachineListView(ListView):
model = MyMachine
template_name = 'site/home.html'
context_object_name = 'machines'
ordering = ['date_delivery']
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
site_title = 'Home'
context["site_title"] = site_title
return context
home.html
{% extends "site/base.html" %}
{% load static %}
{% block content %}
{% for machine in machines %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">{{ machine.date_delivery|date:"d.F Y" }}
</small>
</div>
<h2><a class="article-title" href="">{{ machine.machine_name }} - {{ machine.machine_serial }}</a></h2>
{% if 'Lidl' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Lidl</p>
{% elif 'Kaufland' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Kaufland</p>
{% else %}
<p class="article-content">{{ machine.use_side }} - {{ machine.machine_model}}</p>
{% endif %}
</div>
</article>
{% endfor %}
{% endblock content %}
everything else is working fine. Thank You in advance!
Upvotes: 2
Views: 65
Reputation: 37319
I see two problems here.
One, you're referencing machines.machine_model
, but machines
is a queryset. I'm somewhat surprised referencing machine_model
on it doesn't just fail with a rendering error. It should be machine.machine_model
, since that's your loop variable.
That leads us to the second problem. machine.machine_model
is a foreign key reference to another model, not a string. There's no string that's in
a model instance (barring defining the membership function yourself). I haven't personally tested but I don't think Django stringifies on the fly (as it will when you reference {{ machine.machine_model }}
). Try it with if ... in machine.machine_model.name
.
Upvotes: 1