I'm learning django by myself and as you can imagine it's quite difficult.
I was trying to make a self-adapting form in a view. The app has a model where are stored all the infos about the form (like the placeholder, id and type of the input fields) via JSON (if there's an easier or smarter way I think it'll be better).
So, in the views file I've passed to the template (picture below) 2 variables which refer to the dict from the object in the picture above.
from django.shortcuts import render
from fattura.models import JobType
import json
def fattura(request):
datas = JobType.objects.all()
for i in datas:
if i.jobType==0:
dts = json.loads(i.inputs)
break
return render(request, 'fattura/fattura.html', {"dts": dts, "inputs": dts["inputs"]})
So, now my scope is to extract the values from the keys "inputType" and "placeholder" in a for statement in the template, in order to insert them into the html file.
<main>
<div >
<div subtitle">Compila tutti i campi correttamente.</div>
{% for campo in inputs %}
<div >
<input id="{{ campo }}" type="{{ inputs.campo.inputType }}" placeholder=" " />
<div ></div>
<label for="{{ campo }}" >{{ inputs.campo.placeholder }}</label>
</div>
{% endfor %}
<button type="text" >Invia</button>
</div>
</main>
With the method above I obviously cannot retrieve anything, but I'm not able to resolve this problem.
This is the view by the way (it is an example, that's why it has only two fields):
CodePudding user response:
The inputs field seems that contains a dictionary; in the template you have
{% for campo in inputs %}
but this is valid for lists, maybe you want to use a nested iterators through dictionaries:
{% for key, value in inputs.items %}
{% if key == 'inputs' %}
{% for input_name, input_value in value.items %}
# {{ input_name }} can be nome, cognome, nascita or ammontare
# {{ input_value }} is the value
{% endfor %}
{% endif %}
{% endfor %}
my advice is to organize better the data inside you json field.