Embed WYMEditor in admin

1.6k views Asked by At

How to add a WYMEditor to admin panel? I'm using it for my user-to-user messaging app and I want to replace my textarea to text editor.

2

There are 2 answers

0
catherine On BEST ANSWER

First, download WYMEditor package here http://www.wymeditor.org/download/

Create widgets.py

from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe

class WYMEditor(forms.Textarea):
    #change this for the exact location of your package in your staticfiles
    class Media:
        js = (
            'js/jquery.js', 
            'wymeditor/jquery.wymeditor.pack.js',
        )

    def __init__(self, language=None, attrs=None):
        self.language = language or settings.LANGUAGE_CODE[:2]
        self.attrs = {'class': 'wymeditor'}
        if attrs:
            self.attrs.update(attrs)
        super(WYMEditor, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        rendered = super(WYMEditor, self).render(name, value, attrs)
        return rendered + mark_safe(u'''<script type="text/javascript">
            jQuery('#id_%s').wymeditor({
                updateSelector: '.submit-row input[type=submit]',
                updateEvent: 'click',
                lang: '%s',
            });
            </script>''' % (name, self.language))

Update your forms.py for message form, like this:

from app_name.widgets import WYMEditor

class MessageAdminForm(forms.ModelForm):
    .....
    body = forms.CharField(widget=WYMEditor())
    .....

That's it and remember put the exact location of your package

1
Wes Winham On

Rather than re-inventing this wheel, I would recommend using something like django-wymeditor.

To use this, taken the included example, just add an admin.py:

from django.contrib import admin
from wymeditor.admin import RichTextAdmin
from example.models import TestModel

class TestModelAdmin(RichTextAdmin):
    pass

admin.site.register(TestModel, TestModelAdmin)