Tony Kyriakidis Tony Kyriakidis - 2 months ago 26
Python Question

Django Boolean Field returns False in template while it actually is True

This is my models.py:

class Sherlock(models.Model):
owner = models.ForeignKey(Owner)
wifi = models.BooleanField('Wifi', default=False)


And this is my views.py that contains more than just one context:

class OwnerDetails(generic.DetailView):
template_name ='owners/venuedetails.html'
model = Owner

def get_context_data(self, **kwargs):
context = super(OwnerDetails, self).get_context_data(**kwargs)

self.pk = Owner.objects.get(pk=self.kwargs['pk'])
featurete_list = FeatureteImage.objects.filter(owner=self.pk)
context['featurete_list'] = featurete_list

sherlock = Sherlock.objects.filter(owner=self.pk)
context['sherlock'] = sherlock
return context


And this is my template:

{% if sherlock.wifi %}
<p>Wifi</p>
{% else %}
<p><s>Wifi</s></p>
{% endif %}


And when i go to /admin i have wifi checked. But i always get a crossed wifi ( the
<s>
tag in the template creates the crossed wifi )

My problem is that even though in my admin I have the wifi field checked and saved it still returns false to the template.

Answer

These lines in your view and template do not match.

sherlock = Sherlock.objects.filter(owner=self.pk)

{% if sherlock.wifi %}

You can't access the wifi attribute on the queryset, you access it on the instance.

If the queryset might contain multiple items, then you can loop through the instances in the template.

{% for s in sherlock %}
    {% if s.wifi %}
    Wifi
    {% endif %}
{% endfor %}

If the queryset should only ever return a single instance, then you can use get() instead of filter().

sherlock = Sherlock.objects.get(owner=self.pk)

You can improve this to handle the case where the object does not exist

try:
    sherlock = Sherlock.objects.get(owner=self.pk)
except Sherlock.DoesNotExist:
    # do something here

Sometimes the get_object_or_404 shortcut is useful for this.

sherlock = get_object_or_404(Sherlock, owner=self.pk)

Finally, note that there is no need to compare to True in the template, just use

{% if sherlock.wifi %}