Тег шаблона Django из переменной
Мне нужно сделать форму с Django, которая может иметь теги "select" или "input" в зависимости от переменной.
.
Вот как я передаю переменную в html (файл: views.py
):
from django.shortcuts import render, redirect
from direzione.models import Jobs, JobType
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.template.defaulttags import register
from login import views as lgnwv
import json
# Create your views here.
@register.filter
def get_item(dictionary,key):
return dictionary.get(key)
@login_required(login_url=lgnwv.login)
def fattura(request):
if request.method =="POST":
if request.POST.get('logout') == 'logout':
logout(request)
return redirect(lgnwv.login)
else:
datas = JobType.objects.get(jobType=0)
dts = json.loads(datas.inputs)
job = Jobs.objects.get(id_job=1)
jobName = job.nome
jobHead = datas.headNome
return render(request, 'fattura/fattura.html', {"dts": dts, "inputs":dts["inputs"], "jobName":jobName, "jobHead":jobHead})
Итак, переменная, содержащая строку 'input'
или 'select'
находится в дикте inputs
(тот, который зацикливается)
Вот моя форма:
<div class="form" style="height:{{ dts|get_item:'height' }}px">
<div class="title">Crea Fattura</div>
<div class="subtitle">Compila tutti i campi correttamente.</div>
{% for key, value in inputs.items %}
<div class="input-container ic2">
<{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off" class="input" type="{{ value|get_item:'inputType' }}" placeholder=" " />
<div class="cut" style="width: {{ value|get_item:'cutWidth' }}px"></div>
<label for="{{ key }}" autocomplete="off" class="placeholder">{{ value|get_item:'placeholder' }}</label>
</div>
{% endfor %}
<button type="text" class="submit">Invia</button>
</div>
Строка, в которой у меня возникает проблема - 7-я:
<{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off" class="input" type="{{ value|get_item:'inputType' }}" placeholder=" " />
В основном, я пытаюсь установить тег из переменной. Ниже я привожу пример:
Пример:
.
Переменная tag
содержит 'input'
или 'select'
,
.
И в зависимости от содержимого, в шаблоне тег будет 'input' или 'select':
<input>
или <select></select>
\
Заранее спасибо.
"value" уже является словарем, верно?
Из документации по шаблонам Django:
Технически, когда система шаблонов встречает точку, она пытается выполнить следующие поиски в таком порядке:
Dictionary lookup
Attribute or method lookup
Numeric index lookup
https://docs.djangoproject.com/en/4.1/ref/templates/language/
Вы должны быть в состоянии просто сказать value.tag и двигаться дальше.