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

问题描述 投票:0回答:2

在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 }}值正确打印。

django django-forms django-templates
2个回答
2
投票
args ={'form1':form1,'count1':int(count1)}

用这个

当你接受输入时,那些总是作为string,因此你需要将它转换为int,然后再与number中的template进行比较


1
投票

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

{% if forloop.counter <= count1|add:"0" %}
© www.soinside.com 2019 - 2024. All rights reserved.