How to add Summernote WYSIWYG Editor in Django

After I created a blog application, biggest hurdle from using it is its admin editor. Anyone who has every used wordpress or any otehr blogging platform will not be OK to use simple text editor. I was searching for options to make the text field something like wordpress. I came across two options tinymce editor and Summernote.

I looked at install steps of tinymce and it looked complicated, I did not try and see if this works. When I looked at Summernote, it look simple and straghtforward and I decided to give it a try. Its very simple and it works perfectly fine.

Here are the steps for installtion

Step#1 Install Summernote package.

Install it just like any other python package. If you are using virtualenv, please make sure you install it in virtualenv

$pip install django-summernote
python -m pip install Pillow

Step#2 Changes in urls.py

Add this to main urls.py file

urlpatterns = [
..
..
    path('summernote/', include('django_summernote.urls')),
..
]
..
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  #add this for media

Step#3 Changes in settings.py

Add django_summernote in installed apps in settings.py file.

INSTALLED_APPS = [
    'blog.apps.BlogConfig', # add this statement
    'ifsccode.apps.IfsccodeConfig', # add this statement
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'django.contrib.sites',
    'django.contrib.sitemaps',
    'django_summernote',          # This is added
]

 

Also add media folder settings at the end of settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

X_FRAME_OPTIONS = 'SAMEORIGIN'

Step#4 Changes in admin.py

Changes in admin.py

from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin

from .models import Post, Category, Comment, Tag


admin.site.register(Category)
admin.site.register(Comment)
admin.site.register(Tag)

...

class PostAdmin(SummernoteModelAdmin):    #added this
    summernote_fields = ('content',)      #added this

admin.site.register(Post, PostAdmin)

Please note that in above table, I have content field under Post

Step#5 Changes in Templates

Finally and most importantly, when you are displaying the field, mark it as safe.

<div id="postdetails">{{post.content|safe}}</div>

once this is done

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.