Django模板中的条件for循环

时间:2020-06-03 14:58:35

标签: django django-views django-templates

我对两个不同的查询集使用相同的模板。

视图:

def events_list_view(request, type):
    events_NMS = dateEvent.objects.filter(a filter)
    events_all = dateEvent.objects.filter(another filter)

    context = {
        'events_NMS': events_NMS,
        'events_all': events_all,
    }

    return render(request, 'events/events_list.html', context)

网址:

    path('events/<type>/', events_list_view, name='events_list'),

如何根据URL中的类型使用events_NMSevents_all?我想在模板中执行以下操作:

  {% if "/events/nms/" in request.path %}
    {% for event in events_nms %}
    {% else %}
      {% for event in events_all %}
      {% endif %}
...rest of for loop...

1 个答案:

答案 0 :(得分:0)

好的,那很容易。我认为:

def events_list_view(request, type):
    if type == 'nms':
        events = dateEvent.objects.filter(a filter)
    else:
        events = dateEvent.objects.filter(another filter)

    context = {
        'events': events
    }

    return render(request, 'events/events_list.html', context)