【问题标题】:Why doesn't the {% empty %} option show when no items available?为什么没有可用项目时 {% empty %} 选项不显示?
【发布时间】:2019-05-31 16:33:09
【问题描述】:

我在 django 模板中设置了一个“for/in”循环,并带有一个“空”选项,但是当我的视图没有产生任何项目时,我得到一个 404 页面而不是我的“空”选项。

我尝试在“if”标签中进行替换,但得到了相同的结果。

模板代码:

{% for item in object_list %}
    <p>{{ item.desc }}
{% empty %}
  <p>Nothing scheduled
{% endfor %}

views.py:

class ItemTodayArchiveView(LoginRequiredMixin, TodayArchiveView):
    login_url = '/admin/'
    redirect_field_name= 'redirect_to'
    date_field = 'airpub_date'
    allow_future= True

def get_queryset(self):
    destination = self.kwargs['destination']
    return Item.objects.filter(airpub_date__gte=date.today()).filter(destination=destination)

当查询集为空时(即,该 airpub_date 没有任何内容),我希望模板页面显示“未安排任何内容”。相反,我得到一个 404 调试页面:

Page not found (404)
Request Method: GET
Request URL:    http://xxx.xxx.xxx/items/atc/today/
Raised by:  items.views.ItemTodayArchiveView
No items available

【问题讨论】:

    标签: django templates tags


    【解决方案1】:

    代码甚至没有到达模板,因为视图首先检查您的查询集不为空。要禁用此检查,请在类中设置 allow_empty = True - 请参阅 the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2019-11-18
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多