django - how can I access the form field from inside a custom widget

前端 未结 2 1576
傲寒
傲寒 2021-01-02 07:37

The below class inherits from the Textarea widget and features javascript code that displays how many characters more a user can enter in a textarea.

2条回答
  •  悲&欢浪女
    2021-01-02 08:06

    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