如果条件标签不能正常工作

时间:2018-03-06 09:07:50

标签: django django-forms django-templates

demo.html

<form method="post">
   {{ form1.as_p }}
</form>
<table class="table table-hover" style="width:80%;">
      <tr>
            <th>Test Case</th>
            <th>File Name</th>
            <th>Coverage </th>
        </tr>

        {% for key, value in d.items %}
           <tr>
               <th>{{ key }} </th>
           </tr>

            {% for k,v in value.items%}
                {% if forloop.counter <= count1 %}
                 <tr>
                      <td>   </td>
                      <td>{{ k }}</td>
                      <td>{{ v }}</td>
                </tr>
                {% endif %}
             {% endfor %}
            {% endfor %}


    </table>

views.py

class home_changetesting(TemplateView):
template_name = 'demo.html'

def get(self, request):

    form1 = SortForm()

    return render(request,self.template_name, {'form1':form1})



def post(self, request):

    form1 = SortForm(request.POST)  
    count1=int

    if form1.is_valid():     
        count1= request.POST.get('sort')
        print(count1)
     args ={'form1':form1,'count1':count1}

    return render(request,self.template_name, args)    

forms.py

class SortForm(forms.Form):

sort = forms.ChoiceField(choices=[(x, x) for x in range(1, 11)], required=False,widget=forms.Select())

如果条件仅在我声明为 {% if forloop.counter <= 2 %} 时才有效,相反,如果我使用变量作为上述代码,它就不起作用。请帮我解决上面代码中的错误。

好像使用{{ count1 }}值正确打印。

2 个答案:

答案 0 :(得分:2)

args ={'form1':form1,'count1':int(count1)}

使用此

当您接受输入时,这些内容始终为string,因此在与int number进行比较之前,您需要将其转换为template >

答案 1 :(得分:1)

您可能正在将count1字符串传递给模板。要比较它,您需要将其转换为视图中的int或使用添加过滤器:

{% if forloop.counter <= count1|add:"0" %}
相关问题