22👍
✅
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs['onclick'] = 'return false;'
4👍
Bernhard’s answer used to work on 1.7 and prior, but I couldn’t get it to work on 1.8.
However this works:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget = forms.widgets.Checkbox(attrs={'onclick': 'return false;'})
- Django: lock particular rows in table
- Django assert failure: assertInHTML('hello', '<html>hello</html>')
- In Django loaddata it throws errors for json format but work properly for yaml format, why?
1👍
I encountered the same problem as James Lin on Django 1.10, but got around it by updating the attrs
dictionary rather than assigning a new widget instance. In my case, I couldn’t guarantee the attribute key existed in the dictionary.
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_checkbox'].widget.attrs.update({'onclick': 'return false;'})
- Django South migration conflict while working in a team
- Python split url to find image name and extension
- Reordering fields in Django model
- Django-import-export – import of advanced fields?
- Is there a Django ModelField that allows for multiple choices, aside from ManyToMany?
0👍
I had to do the same thing, but not necessarily on initialisation. In my case I had to set-up a specific id to work with my AJAX function. The answer was similar to kmctown above, but I didn’t use the init, just created a normal function within the form class as per below:
def type_attr(self, id_val):
self.fields['type'].widget.attrs.update({'id':id_val})
Then, in views:
form=YourForm(request.POST or None)
form.type_attr(id_val)
This worked in my case.
- Hide password field in GET but not POST in Django REST Framework where depth=1 in serializer
- Sending CSRF Tokens via Postman
- Project management/build tools for a Django project?
- Limiting the queryset for ManyToMany MultipleSelect in Django admin
Source:stackexchange.com