Thursday, July 5, 2012

Re: insert html into a form from Django code (not template)

On Thu, Jul 5, 2012 at 1:15 PM, angelika <angelika.olsson@gmail.com> wrote:
> I've written a longer post here:
> http://stackoverflow.com/questions/11341118/printing-repeated-django-form-fields-individually
> explaining what I need. Either a way to individually print out the fields in
> a loop or a way to insert html from the backend. Maybe it's just not
> possible to do this in Django and then I will think of another solution, but
> I would like to make sure before I solve it another way.
>
> /Angelika
>

Of course it is possible. When you create the fields in the init
method, make sure they are given distinct names. Store the names of
the generated fields in a list on the form object, and then provide an
iterator method that yields the variable fields in the order you want.
Eg:

class MyForm:
def __init__(self, *args, **kwargs):
self._variable_fields = [ ]
for ....:
field_name_id = 'field_name_%d' % val_id
field_email_id = 'field_email_%d' % val_id
self.fields[field_name_id] = forms.FooField(...)
self.fields[field_email_id] = forms.FooField(...)
self._variable_fields.append((field_name_id, field_email_id))

def variable_fields(self):
for field_name_id, field_email_id in self._variable_fields:
yield self[field_name_id], self[field_email_id]

In your template:

{{ form.static_named_field1 }}
{{ form.static_named_field2 }}

{% for field_name, field_email in form.variable_fields %}
{{ field_name }}
{{ field_email }}
{% endfor %}

Hope that helps

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate