首页 > 解决方案 > 在 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>

标签: djangodjango-templates

解决方案


实际上,您可以创建自定义模板标签以使您的解决方案正常工作:

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

但是在阅读了您的更新之后,我相信您可以为您的用例找到更清洁的东西。


推荐阅读