Home > Back-end >  Tag of a Django Template from a variable
Tag of a Django Template from a variable

Time:08-29

I need to do a form with Django which can have both "select" or "input" tags, depending on a variable.
Here's how I pass the variable to the html (file: 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})

So, the variable that contains the string 'input' or 'select' is into the dict inputs (the one that's looped)
This is my form:

<div  style="height:{{ dts|get_item:'height' }}px">
  <div >Crea Fattura</div>
  <div >Compila tutti i campi correttamente.</div>
  {% for key, value in inputs.items %}
  <div >
    
    <{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off"  type="{{ value|get_item:'inputType' }}" placeholder=" " />
    
    <div  style="width: {{ value|get_item:'cutWidth' }}px"></div>
    <label for="{{ key }}" autocomplete="off" >{{ value|get_item:'placeholder' }}</label>
  </div>
  {% endfor %}
  <button type="text" >Invia</button>
</div>

The line where I have the problem is the 7th: <{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off" type="{{ value|get_item:'inputType' }}" placeholder=" " />

Basically, I'm trying to set a tag from a variable. I'm leaving an example below:
Example:
The variable tag contains 'input' or 'select',
And depending on the content, in the template the tag will be 'input' or 'select':
<input> or <select></select>\

Do I need to use an If statement or there's a way to put the value of a variable in an html tag?

CodePudding user response:

"value" is already a dictionary right?

From the Django template documentation:

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

Dictionary lookup
Attribute or method lookup
Numeric index lookup

https://docs.djangoproject.com/en/4.1/ref/templates/language/

You should be able to just say value.tag and move along.

  • Related