Creating a custom list/dictionary of BoundFields for a django Form (emulating form.hidden_fields)
Okay, I have a somewhat complicated form with a lot of complicated business logic, and as a result I'm actually generating fields on the fly when the form is created. I need to be able to access the fields in the template but of course since they're generated I can't just do something like {{ form.fieldname }}
because in this case fieldname
is actually made from a variable.
I tried something like this in the form:
def __init__(self, *args, **kwargs):
# initialization code is here, so let's just skip that
self.items = kwargs.pop("items", [])
self.my_fields = []
for item in self.items:
self.fields['item_%d' % item.pk]=forms.CharField(required=True, label=item.name)
self.my_fields.append(self.fields['item_%d' % item.pk])
However, in the template, when I try this:
{% for field in self.my_fields %}
{{ field }}
{% endfor %}
I get something like <django.forms.fields.CharField object at 0x2b08aeb45810>
Is there a way to do this so I can get the actual rendered field?
Update
Looks like rendered fields have a type django.forms.forms.BoundField
and are created when __getitem__
is called on the field
object. Basically, I guess I need some way to create something that behaves like hidden_fields
only contains my field开发者_开发百科s instead.
Figured it out. In order to make sure __getitem__
was triggered, I needed to set the fields like this:
def __init__(self, *args, **kwargs):
# initialization code is here, so let's just skip that
self.items = kwargs.pop("items", [])
self.my_fields = []
for item in self.items:
self.fields['item_%d' % item.pk]=forms.CharField(required=True, label=item.name)
self.my_fields.append(self['item_%d' % item.pk])
精彩评论