user1187968 user1187968 - 1 year ago 123
Python Question

Django form field dynmaic attr

How do I set the the attributes dynamicallyfor a form field in a Django form?
Right now I can use the follwing for a fixed attribute.

time_record = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off'}))

Let's say I want to dynamically to add a attribute called "data-record" during the form instantiation, how would I do that?

Answer Source

You can add it to the attrs dictionary of the widget of the field:

def __init__(self, **kwargs):
    super(MyForm, self).__init__(**kwargs)

    self.fields['time_record'].widget.attrs['data-record'] = ''
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download