Try this:
def random_fact():
fact = Fact.objects.order_by('?').first()
return {'fact': fact}
Question
I got a simple templatetag which returns a random fact. When there are no facts in the database, I'm getting an exception value list index out of range. I wrapped the query set with try, except* and also checking if there is a fact in the template. You can see the code below:
fact.py
# template tag
from django import template
from facts.models import Fact
register = template.Library()
def random_fact():
try:
fact = Fact.objects.order_by('?')[0]
except Fact.DoesNotExist:
fact = None
return {'fact': fact}
register.inclusion_tag('facts/fact.html')(random_fact)
fact.html
<!-- Random Fact Start -->
<div class="panel panel-default sidebar">
<div class="panel-heading">
<h3 class="panel-title">Did you know?</h3>
</div>
<div class="panel-body">
{% if fact %}
<p class="text-left">{{ fact.fact }}</p>
<p class="text-right"><i class="fa fa-link"></i> <i><a href="{{ fact.website }}" target="_blank">{{ fact.author }}</a></i></p>
{% else %}
<p class="text-left">There are currently no studying tips!</p>
{% endif %}
</div>
</div>
<!-- Random Fact End -->
Solution
Try this:
def random_fact():
fact = Fact.objects.order_by('?').first()
return {'fact': fact}
OTHER TIPS
Fact.objects.order_by('?')
expression doesn't throw DoesNotExist
in case of nothing found - it becomes an empty list. Getting 0-th item on an empty list throws IndexError
, catch it:
def random_fact():
try:
fact = Fact.objects.order_by('?')[0]
except IndexError:
fact = None