1👍
Use a different template filter
I don’t think that the getattr
template filter is very suitable for your purposes. I don’t like the has_key
check, because it will return False, even though 'field_name' in Form
is True
.
You might be able to get the template tag to work by setting attributes on the form, but it seems hacky to me. A better approach would be to use a different template filter.
If you have a form
, then you can access the field answer_1
with form['answer_1']
. Using this knowledge, it’s easy to create a more suitable template filter.
@register.filter(name='get_form_field')
def get_form_field(form, field_name):
try:
return form[field_name]
except KeyError:
return settings.TEMPLATE_STRING_IF_INVALID
Then, in your template, you can do
{{ form|get_form_field:"answer_1" }}
Or, if you are using the with
template tag:
{% with "answer_1" as ans %}
{{ form|get_form_field:ans }}
{% endwith %}
Or try a different approach
Actually, I’m not sure that you need a special template filter at all. You could add a method to your form, that returns a list of the fields you want to display.
class MyForm(forms.Form):
def answer_fields(self):
return [self['answer_%d' % x] for range(1, 5)]
Then in your template, loop through the list and render them.
{% for field in form.answer_fields %}
{{ form.answer_fields }}
{% endfor %}