1
我認爲我的查詢集正在返回一個空列表而不是「不存在的錯誤」。我希望它返回一個錯誤,以便我可以返回一個替代消息。 HTML正在返回一個空的子彈點而不是所需的消息。查詢集返回空列表而不是錯誤
view.py
def results(request, foo_id):
template_name = 'results.html'
foo = Foo.objects.get(id=foo_id)
foo_id = foo_id
try:
foobars = FooBar.objects.filter(foo__foo=foo.foo)
return render(request, template_name, {'foobars': foobars,
'zipcode':zipcode, 'foo_id':foo_id})
except FooBar.DoesNotExist:
message = 'Sorry there are no FooBar with that foo'
return render(request, template_name, {'message':message,
'foo_id':foo_id})
models.py
class Foo(models.Model):
foo = models.IntegerField(null=True)
class FooBar(models.Model):
foo = models.ForeignKey('Foo')
title = models.CharField(max_length=100)
description = models.CharField(max_length=400, null=False, blank=True)
def __str__(self):
return self.title
results.html
<html>
<h2>Title</h2>
<ul id='id_results'>
{% for foobar in foobars%}
<li>{{ foobar.name }}</li>
{% empty %}
<li> {{ message }} </li>
{% endfor %}
</ul>
<a href= "/new_foobar/">New FooBar </a>