python - Django 模板 if 在带有列表索引的 for 循环中

我想使用列表的索引来获取列表的 values 。

我在views.py中有一个列表

视图.py

def home(request):

 my_list=[("xy","abc","abcd"),("abcd","abc","xy")]
 
 context={ "list"=my_list}

return render(request, 'index.html',context)

索引。html

{% for id in list%}
  
    {% if id.1 =='abc' %}

          {{id.0}}="Core user" 
           
          {{id.0}}

    {% else %}

       {{id.0}}

    {% endif %}

{% endfor %}

因此,如果条件满足,列表的新 values 将是

[("xy","核心用户","abcd"),("abcd","核心用户","xy")]

我收到了语法错误。请让我知道我做错了什么以及如何解决这个问题?

回答1

元组数据类型不能修改。

因此,将元组数据类型转换为数组数据类型。

我推荐 https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#writing-custom-template-filtershttps://docs.djangoproject.com/en/4.0/ref/templates/builtins/#with with Shallow Copy

在views.py中

my_list=[["xy","abc","abcd"],["abcd","abc","xy"]]

在 custom.py 中

def set_core_user(my_list: list[str]) -> list[str]:
    my_list[1] = "Core user"
    return my_list

在 html

{% for id in list%}

{% if id.1 =='abc' %}

      {{id.0}}="Core user" 
       
      {{id|set_core_user}}

{% else %}

   {{id.0}}

{% endif %}

{% endfor %}

相似文章

python - python 猜数字游戏,猜多

我正在学习编程1并且正在做1-100的猜数游戏,我需要一个命令,如果我猜超过100,程序会看到它并告诉我,我不知道我应该如何得到这个答案。我已经猜到我认为该命令会是什么样子以及它最远的地方,但如果我完...

随机推荐

最新文章