django - 在 django 中避免两个 forloop 的任何有效方法
问题描述
在 django 中任何更好或更有效的方法
{% for list1item in list1 %}
{% for list2item in list2 %}
{% if forloop.counter == forloop.parentloop.counter %}
{{ list1item }} {{ list2item }}
{% endif %}
{% endfor %}
{% endfor %}
我想做这样的事情,但不工作。
{% for list1item in list1 %}
{% with forloop.counter as i %}
{{ list2.i }}
{% endwith %}
{% endfor %}
更新!其实故事就在这里! 这是我的forms.py
from django import forms
from .models import MedicalRecords
class UpdateMedicalRecordForm(forms.ModelForm):
class Meta:
model = MedicalRecords
fields = ("title", "file", "doctor")
widgets = {
"title": forms.Textarea(attrs={"rows": "", "class": "form-control"}),
}
我想要一个带有它的实例的每个病历表格的列表,所以我[UpdateMedicalRecordForm(instance=x) for x in medicalrecords]
用来为每个病历创建表格。我的view.py是
...
medicalrecords = get_list_or_404(MedicalRecords,somefilterings..)
forms = [UpdateMedicalRecordForm(instance=x) for x in medicalrecords]
...
然后在模板中访问我正在使用的每种形式的医疗记录
<form method="POST" enctype="" class="">
<div class="modal-body">
<div class="form-group">
{% csrf_token %}
{% for form in forms reversed %}
{% if forloop.counter == forloop.parentloop.counter %}
{{ form.as_p }}
{% endif %}
{% endfor %}
</div>
<div class="submit-section text-center">
<button type="submit" class="btn btn-primary submit-btn">Submit</button>
<button type="button" class="btn btn-secondary submit-btn" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
解决方案
实际上,您可以创建自定义模板标签以使您的解决方案正常工作:
# templatetags/custom_tags.py
from django import template
register = template.Library()
@register.filter
def get_index(obj, index):
"""
Try to get value from a list object with an index given in parameter.
Return an empty string if index doesn't exist
"""
try:
return obj[index]
except IndexError:
return ""
然后在您的模板中,您可以执行以下操作:
{% load custom_tags %}
{% for list1item in list1 %}
{{ list2|get_index:forloop.counter }}
{% endfor %}
但是在阅读了您的更新之后,我相信您可以为您的用例找到更清洁的东西。
推荐阅读
- azure-service-fabric - 服务结构是否为每个有状态分区创建单例实例?
- android - 删除expandablelistview最后一项中的分隔视图
- java - install4j Splashscreen 停留在应用程序启动之外
- networking - 小型封闭网络中的多个 CoAP 服务器
- python - 遍历 Pandas 中选定的列和行
- java - @@@ 中止:LIBC:参数是无效的堆地址
- lua - .ahk 脚本为 LGS 重新制作
- c# - 如何使用 GeckoFx 发布
- c# - 如何在 DropDownList 中绑定数据
- php - PHP:如何使用超过 3 个具有相同函数名称的特征?我想使用所有相同名称的函数