Home > Mobile >  How to solve Django form attribute not working
How to solve Django form attribute not working

Time:12-17

All form attributes work fine, except on textarea. This is my code:

# forms.py
class VineyardForm(forms.ModelForm):
    class Meta:
        model = Vineyard
        fields = [
            "name", "text", "wine_rg", "wines", "size", "grapes",
            "owner", "visits", "region", "regions", "cover"
        ]
        labels = {
            "name": "Vineyard or Property Name",
            "text": "Vineyard Description and Information",
            "wine_rg": "Wine Region and Country",
        }
        widgets = {
            "name": forms.TextInput(attrs={"placeholder": "Name of your vineyard..."}),
            "text": forms.Textarea(attrs={"placeholder": "something"}),
            "wine_rg": forms.TextInput(attrs={"placeholder": "Where is your vineyard located: region and country..."}),
        }

When I look into the page inspector, I see this code: enter image description here

I think the problem is because I'm using ckeditor. Any suggestion?

CodePudding user response:

The RichTextFormField in the django-ckeditor package is poorly coded, and overwrites any update made with the widgets option:


class RichTextFormField(forms.fields.CharField):

    def __init__(self, config_name='default', extra_plugins=None, external_plugin_resources=None, *args, **kwargs):
        kwargs.update({'widget': CKEditorWidget(config_name=config_name, extra_plugins=extra_plugins,
                                                external_plugin_resources=external_plugin_resources)})
        super(RichTextFormField, self).__init__(*args, **kwargs)

However, you can update the widget attrs in the ModelForm constructor:



class VineyardForm(forms.ModelForm):

    def __init__(self, *args, **kw):
        super(VineyardForm, self).__init__(*args, **kw)
        self.fields['text'].widget.attrs['placeholder'] = "something"
    
  • Related