Using ckEditor on selective text areas in django admin forms

喜欢而已 提交于 2019-12-07 15:20:49

问题


I want to apply ckeditor on specific textarea in django admin form not on all the text areas.

Like snippet below will apply ckeditor on every textarea present on django form:

class ProjectAdmin(admin.ModelAdmin):

    formfield_overrides = 
    {models.TextField: {'widget': forms.Textarea(attrs={'class':'ckeditor'})}, }

    class Media:
        js = ('ckeditor/ckeditor.js',)

but i want it on a specific textarea not on every textarea.


回答1:


You have couple of options.

I think the simplest is if you use Django 1.2, then you have to create custom form for your admin and use 'widgets' option:

ProjectForm(forms.ModelForm)
    class Meta:
        model = Project
        widgets = { 
           'field_1' : forms.Textarea(attrs={'class':'ckeditor'}),
           'field_2' : forms.Textarea(attrs={'class':'ckeditor'}),
            ...
        }

If you use older version of Django you can still use custom form, just override the field, in which you want ckEditor, in the form:

ProjectForm(forms.ModelForm)
    class Meta:
        model = Project

    field_1 = forms.SomeField(label=u'my label', widget=forms.Textarea(attrs={'class':'ckeditor'}))

Alternative:

ProjectForm(forms.ModelForm)
    class Meta:
        model = Project

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        self.fields['field_1'].widget = forms.Textarea(attrs={'class':'ckeditor'})

Finally for all three options, you set your ProjectAdmin to use ProjectForm:

class ProjectAdmin(admin.ModelAdmin)
    form = ProjectForm


来源:https://stackoverflow.com/questions/2920350/using-ckeditor-on-selective-text-areas-in-django-admin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!