ionalchemist
ionalchemist

Reputation: 418

Manual Django Form Display

I want to manually render the form in my template, but what I'm trying is not yielding the expected result, and it is not apparent as to why.

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['field1'] = forms.BooleanField()
        self.fields['field2'] = forms.BooleanField()
        systems = System.objects.all()
        for i in range(len(systems)):
            self.fields['s' + str(i)] = forms.BooleanField()
        self.fields['field3'] = forms.BooleanField()

        self.initial_fields = [self.fields['field1'], self.fields['field2']]

now when I do this in my template:

{% for field in form.visible_fields %}
    {{ field }}
{% endfor %}

it returns what you would expect...after looking up the method visible_fields it simply returns a list of fields. So in theory, if I create my own list of fields as with self.initial_fields, the form generator should render the following same as above:

{% for field in form.initial_fields %}
    {{ field }}
{% endfor %}

but instead I get this output in my template:

<django.forms.fields.BooleanField object at 0x000001242F51E588> 
<django.forms.fields.BooleanField object at 0x000001242F51E400>

I'm assuming I'm missing some initialization of the field itself? I don't understand why one works and the other doesn't. Anyone know?

Upvotes: 0

Views: 48

Answers (1)

devdob
devdob

Reputation: 1504

You need to get the bound field object and not the field itself. It's not really a clean way of doing so, but if you are looking to hack around it, you should do like so,

...
self.initial_fields = [self.fields['field1'].get_bound_field(self, 'field1'),
                       self.fields['field2'].get_bound_field(self, 'field2')]
...

Hope this helps!

Upvotes: 1

Related Questions