如何在Django模板中动态地从上下文(对象)中获取值

qzlgjiam  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(143)

我是一个django新手,我试图直接在模板中动态地从对象中获取值,但似乎什么都不起作用:这是我在Django模板中的内容:

{% for key, value in edit.changes.items %}
<p>{{ translator.get(key) }}</p>

我也试过这个:

{% for key, value in edit.changes.items %}
<p>{{ translator[key] }}</p>

这是一种观点:

def medical_record_edit_list(request, pk):
    translator = {
        "appointment_date" :"Fecha",
        "diagnosis_type" : " Tipo de Diagnóstico",
        "main_diagnosis" : "Diagnóstico Principal (CIE-10)",
        "related_diagnosis" : "Diagnóstico Relacionado (CIE-10)",
        "objective" : "Objetivo",
        "mental_exam" : "Exámen Mental",
        "development" : "Desarrollo",
        "employed_interventions" : "Intervenciones Utilizadas",
        "evaluation_instruments" : "Instrumentos de Evaluación",
        "agreements" : "Acuerdos",
        "therapeutic_work" : "Expectativas de la Consulta",
        "evaluation_instruments" : "Instrumentos de Evaluación",
        "remission" : "Remisiones y Contrarremisiones",
        "finality" : "Finalidad",
        "external_cause" : "Causas Externas",
        "conduct" : "Conducta",
        "exit_state" : "Estado de Salida",
        "exit_diagnosis" : "Diagnóstico de Egreso (CIE-10)",
        "exit_condition" : "Condición de Salida"
    }
    medical_record_entry = MedicalRecordEntry.objects.get(pk=pk)
    edit_list = MedicalRecordEdit.objects.filter(medical_record_entry=medical_record_entry).order_by("edit_date")
    return render(request, 'medical_record/medical_record_edit_list.html', {'edit_list':edit_list,
     'medical_record_entry':medical_record_entry, 'translator': translator})

我只是想得到类似{{ context.appointment_date }}的输出-但是对于上面for循环的每个键

mfuanj7w

mfuanj7w1#

你不需要直接在模板中做一些事情。当然,你可以创建自己的django模板标签,在上面你可以找到很多答案,如何在django中做到这一点。
但这一切真的是不正确的,你可以做的一切事情更简单:

def medical_record_edit_list(request, pk):
    # your staff, define translator and edit_list there

    edited = (((translator[key], key, val) for key, val in edit.changes.items)
               for edit in edit_list)
    return render(request, 'medical_record/medical_record_edit_list.html', {
           'edit_list':edit_list,
           'medical_record_entry':medical_record_entry, 
           'translator': translator,
           'edited': edited 
           })

之后在模板中:

{% for edited_item  in edited %}
    {% for translation, key, value in edited_item %}
        <p>{{ translation }}</p>
    {% endfor %}
{% endfor %}

相关问题