首页 > 解决方案 > How can I create a if using the value of select?

问题描述

Hello I have the following code :

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

Then I want to do something like this ;

{%  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 %}

How can I do this ?

标签: javascriptpythonhtmldjango

解决方案


看看这种方法是否有帮助。

<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/


推荐阅读