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

前端 未结 2 1564
傲寒
傲寒 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:00

    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
    

提交回复
热议问题