Dmitry
Dmitry

Reputation: 570

Customize ckeditor in django admin form

I need configure custom params (toolbars, width and height) of ckeditor for only one field in my AdminForm

class BlogAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BlogAdminForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget = CKEditor(attrs={'cols': 100, 'rows': 25})

How to set specific parameters of ckeditor (such as «toolbarGroups», «width», «height» etc) for only this field?

Upvotes: 2

Views: 2012

Answers (1)

rbell01824
rbell01824

Reputation: 189

The best way of overriding field attributes I've found is to use a custom ModelForm thus:

class XAdminForm(forms.ModelForm):
    name = forms.CharField(label='Name', max_length=100,
                       widget=forms.TextInput(attrs={'size': '100'}))
    something = forms.CharField(label='Something', max_length=SOME_MAX_LENGTH,
                          widget=forms.Textarea(attrs={'rows': '10', 'cols': '100'}))
    note = forms.CharField(label='Note', max_length=NOTE_MAX_LENGTH,
                       widget=forms.Textarea(attrs={'class': 'ckeditor'}))

class Meta:
    model = x


class XAdmin(admin.ModelAdmin):
    model = X
    form = XAdminForm

    class Media:
        js = ('/static/js/ckeditor/ckeditor.js',)
admin.site.register(X, XAdmin)

You can inject additional attributes or JS either in the ModelForm or ModelAdmin as needed.

The technique is easy enough but apparently not widely known or documented.

Upvotes: 1

Related Questions