Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using python dictionaries in a django template

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).

all the objects inside the module

an example of an object inside the module

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

this is my views.py file

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.

enter image description here

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):

enter image description here

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading