{% empty %} does not work in django template

时间:2018-02-03 09:54:14

标签: django django-templates

if works correctly but empty does not work, here is my code:

{% for answer in ans|slice:":3" %}
{% for course in crs %}
{% if answer.course_id == course.id %}

  <h4 class="w3-text-blue">{{answer.course}}</h4>

{% endif %}
{% empty %}
<h1>empty</h1>
{% endfor %}
{% endfor %}

and this is my views:

class CourseListView(ListView, LoginRequiredMixin):
model = Course
template_name = 'course_list.html'
def get_context_data(self, **kwargs):
    context_data = super(CourseListView, self).get_context_data(**kwargs)
    context_data['crs'] = Course.objects.raw('SELECT * FROM ertaapp_course where prof_id=%s',[self.request.user.id])
    context_data['ans'] = Answer.objects.raw('SELECT * FROM ertaapp_answer')
    return context_data

1 个答案:

答案 0 :(得分:1)

Why you want to do that, just use {% if %} and {% else %}:

views.py

def get_context_data(self, **kwargs):
    context_data = super(CourseListView, self).get_context_data(**kwargs)
    context_data['crs'] = Course.objects.raw('SELECT * FROM ertaapp_course where prof_id=%s',[self.request.user.id])
    ans = Answer.objects.all()
    context_data['ans'] = ans
    context['ans_count']=ans.count()
    return context_data

Now, in html template

{% if ans_count > 0 %}
    {% for answer in ans|slice:":3" %}
        {% for course in crs %}
            {% if answer.course_id == course.id %}
                <h4 class="w3-text-blue">{{answer.course}}</h4>
            {% endif %}
        {% endfor %}   
    {% endfor %}
{% else %}
     <h1>empty</h1>
{% endif %}