python - Iterate over Django custom Form -


i trying create dynamic form, varying number of charfields. want able display them @ in semi-arbitrary places in form. approach create iterable function fielded right self.fields[index]. however, when this, literally see this:

<django.forms.fields.charfield object @ 0x80bae6be0> <django.forms.fields.charfield object @ 0x80bae6f98> <django.forms.fields.charfield object @ 0x80bae6da0> 

how make charfield() render expected?

my code below:

class implementationform(forms.modelform):     """     specifies implementation of given control.     """     class meta:         model = implementation         fields = ['implemented', 'scope', 'separate']      def __init__(self, *args, **kwargs):          control = kwargs.pop('control')          super(implementationform, self).__init__(*args, **kwargs)         self.fields['separate'].widget.attrs.update({'class': 'separate'})         self.fields['scope'].widget.attrs.update({'class': 'scope'})          substatement in control.substatement.all():             self.fields['statement_%s'%substatement.pk] = forms.charfield()      def subfield(self):         print("comes here")         index in self.fields:             if index[:10] == 'statement_':                 yield self.fields[index] 

the template this:

{% x in myform.subfield %} {{ x }} {% endfor %} 

what looking form's boundfields. e.g. {{ form.email }} iterating on field instances (not form's boundfield instances wraps field instances) e.g. {{ form.field.email }}. why getting

<django.forms.fields.charfield object @ 0x80bae6da0>

result template. see: https://stackoverflow.com/a/671305/3035260

also see django's documentation: https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.boundfield

try dirty way (see edit below better solution):

{# iterate on list of field instances #} {% x in myform.subfield %}   {# find matching boundfield instance #}    {% field in myform %}     {% if field.field == x %}       {# matching boudfield instance found, display it. #}       {{ field }}     {% endif %}   {% endfor %} {% endfor %} 

edit: came across better (less dirty) approach: field has

get_bound_field(self, form, field_name)

method according docs: https://docs.djangoproject.com/en/1.10/_modules/django/forms/fields/#field.get_bound_field

so, in subfield method in last line (the 'yield' line), try this:

yield self.fields[index].get_bound_field(self, index) 

then, template remain same:

{% x in myform.subfield %} {{ x }} {% endfor %} 

and should work intended.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -