如何使用select的值创建if?

2024-05-28 20:52:24 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我有以下代码:

<select name="test1" class="form-control">
                <option value=""></option>
                {%  for test in tests %}
                    <option value="{{ test.id }}">{{ test.name }}</option>
                {% endfor %}
            </select>

然后我想做这样的事情

{%  if test.id %} 

# show something but I need to know if there is sometinh in test.id
# I think the problem comes from this line, in fact I want this condition is realised if test.id is not empty else the condition is not realised.

{% endif %}

我该怎么做


Tags: the代码nameintestidifis
1条回答
网友
1楼 · 发布于 2024-05-28 20:52:24

看看这种方法是否有帮助

<select name="test1" class="form-control">
                <option value=""></option>
                {%  for test in tests %}
                    <option value="{{ test.id }}">{{ test.name }}</option>
                  {%  if test.id %} 
                    #show what you want..
                   {% empty %} <<<<======
                    #if empty do this...
                  {% endif %}
                {% endfor %}
            </select>

举个例子:

import Http Response from django 
from django.shortcuts import render 

#create a function 

def your_view(request): 
    # create a dictionary 
    context = { 
    #enter code here
        "data" : [], 
    } 
    # return response 
    return render(request, "template.html", context) 

现在在templates/template.html中

{% for i in data %} 
    <div class="row"> 
        {{ i }} 
    </div> 
    {% empty %} 
    <h4>There is nothing in this list</h4> 
{% endfor %} 

您可以更好地查看此链接: https://www.geeksforgeeks.org/for-empty-loop-django-template-tags/

相关问题 更多 >

    热门问题