user7890203
user7890203

Reputation: 11

Manually render Django form fields with variable label

I am creating forms with dynamic fields (and field names) using the below code

class BuyItemForm (forms.Form):
    def __init__(self, inventory_list,  *args, **kwargs):
        super(BuyItemForm, self).__init__(*args, **kwargs)
        for item in inventory_list:
            self.fields["count%s"%item.item_name] = forms.IntegerField()
            self.fields["price%s"%item.item_name] = forms.FloatField()

So I get a form that has field names like "counteggs", "priceeggs", "countmilk", etc... when these items are in the inventory_list

I now want to render the fields manually in my template. I am able to iterate through the set of fields, for example

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

But I am unable to pick out each field individually by using the field name in a string. I have tried

{{ form.fields['counteggs'] }} 

but this doesnt work. Any ideas how I can make this work?

Upvotes: 1

Views: 793

Answers (2)

user7890203
user7890203

Reputation: 11

So, I found a rather convoluted way of doing this by creating a filter in views.py that receives the form and a key as parameters. It iterates through the form till a field that has a label matching the key is found.

@register.filter
def get_countitem(myform, key):
    for field in myform:
        if field.label.lower() == key.lower():
            return field
    return "none"

and in the template

{{ form|get_countitem:"counteggs" }}

It works. I can get my template to render form fields by passing the field label in a string but doesnt seem like a particularly elegant solution to me. Any other ideas are most welcome.

Upvotes: 0

NS0
NS0

Reputation: 6096

Did you try {{ form.fields.counteggs }} ? In the templates, dictionaries are accessed with dot notation.

Upvotes: 1

Related Questions