Tony Kyriakidis Tony Kyriakidis - 1 month ago 12x
Python Question

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

This is my

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

And this is my 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) = Owner.objects.get(pk=self.kwargs['pk'])
featurete_list = FeatureteImage.objects.filter(
context['featurete_list'] = featurete_list

sherlock = Sherlock.objects.filter(
context['sherlock'] = sherlock
return context

And this is my template:

{% if sherlock.wifi %}
{% else %}
{% endif %}

And when i go to /admin i have wifi checked. But i always get a crossed wifi ( the
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.


These lines in your view and template do not match.

sherlock = Sherlock.objects.filter(

{% 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 %}
    {% endif %}
{% endfor %}

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

sherlock = Sherlock.objects.get(

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

    sherlock = Sherlock.objects.get(
except Sherlock.DoesNotExist:
    # do something here

Sometimes the get_object_or_404 shortcut is useful for this.

sherlock = get_object_or_404(Sherlock,

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

{% if sherlock.wifi %}