Opened 4 years ago

Closed 4 years ago

#26505 closed Bug (invalid)

django form dynamic attribute lookup

Reported by: Igor Belo Owned by: nobody
Component: Forms Version: 1.9
Severity: Normal Keywords: django-forms custom-templatetag dynamic-attribute-lookup
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I'm facing an issue, and can't figure out how to solve it.

I have the following form in my application:

class ContentForm(ModelForm):
        class Meta:
            model = Content
            fields = ('url_1','url_2','url_3','url_4','url_5',)
            widgets = {
                'url_1': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
                'url_2': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
                'url_3': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
                'url_4': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
                'url_5': forms.URLInput(attrs={'class': 'form-control', 'maxlength': 100}),
            }

What I'm trying to do is to generate those url fields dynamically through a loop. I took this approach (which implements a template tag for dynamic attribute lookup):

    {% for i in 12345|make_list %}
        {% with url='url_'|add:i %}
          {{ form|getattribute:url }}
        {% endwith %}
    {% endfor %}

However it's not working. Django doesn't render the input field and complains that my form object doesn't have an attribute called url_1 for example. If I call the url_1 attribute for the same form directly it works. I checked it many times and the form object id is the same in all contexts (template, view and custom template tag).

The implementation of the getattribute template tag is the same as here.

ps.: django version running is 1.9.2

Change History (1)

comment:1 Changed 4 years ago by Tim Graham

Resolution: invalid
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top