user1187968 user1187968 - 8 months ago 32
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?


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'] = ''