6👍
Technically, a Widget doesn’t have to have a direct relationship back to a Field, so you don’t do this.
Looking at the source of CharField
, you can see that it has a widget_attrs
method which automatically adds the maxlength
attribute to TextInput
/ PasswordInput
fields.
I suggest you use a custom Field which overrides this method and adds an attribute for your custom Widget.
Also, I’m not sure that leaving it in attrs
is a good idea anyway – the <TextArea>
will be rendered with an invalid max_length
argument. Perhaps you should be pop()
ing it off instead?
16👍
Although not required for solving your problem, access to the form or form field may be indeed useful sometimes. See the full answer at another question, but in short, you can bind the form or field to the widget manually in form __init__
:
class MyForm(forms.ModelForm):
foo = forms.ModelChoiceField(Foo.objects, widget=CustomWidget())
class Meta:
model = Bar
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['foo'].widget.form_instance = self
- Django_auth_ldap no module named ldap
- Django generate csv file on view and download
- Django: Custom User Model fields not appearing in Django admin
- How can I create a partial search filter in Django REST framework?
- Celerybeat automatically disables periodic task