Home > Net >  Django form fields to HTML
Django form fields to HTML

Time:12-16

I'm crating fields in a for loop and storing them in a list in a Django form. When trying to place the fields in the HTML file, it appears to be printing the object.

Something like this: <django.forms.fields.IntegerField object at ...>

My HTML looks like this:

{% for i in form.list %}
    {{i}}
{% endfor %}

This is how I create the list:

l1 = [] #List that contains names 
l2 = [] #List that contains other names 
result = {} 
for i in l1: 
   for j in l2: 
      v_name = i   '_'   j 
          result[v_name] = forms.IntegerField()

How can I convert that string to an actual input?

CodePudding user response:

You can add fields to the self.fields dictionary in Form.__init__ to dynamically add fields to a form.

class MyForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for i in l1: 
            for j in l2: 
                v_name = i   '_'   j 
                self.fields[v_name] = forms.IntegerField()

This can be used like a regular form, or iterated over

{{ form }}

{% for field in form %}
    {{ field }}
{% endfor %}
  • Related