How to use Summernote editor in Django?

In this Python Django tutorial, we will come to know about the use and implementation of another type of rich text editor in our Django project. In this tutorial, we will discuss how to use the Summernote Editor in Django.

Along with that, we will implement the necessary steps to integrate the Summernote Editor in our Django project and Django Forms using examples.

First of all, we will understand what is Summernote in Django.

Introduction to Summernote Editor in Django

  • Summernote is a basic WYSIWYG (What You See Is What You Get) editor which creates and edits our project content easily.
  • It supports widely used frameworks like Django, jQuery, Bootstrap, and AngularJS.
  • This is an open-source Javascript library that allows us to edit and create HTML content.

How to use Summernote editor in Django?

To integrate Summernote Editor in Django, we need to install some packages. In this case, we will use django-summernote package. After installing this, we can use django-summernote with Django models and Django forms as well.

Here are the steps that we can follow to integrate and use the Summernote in Django.

Step-1: Create & activate a virtual environment in Python

First, we will create a virtual environment for our Django project. To create an environment, we will use the code mentioned below in a command prompt or any terminal.

> python -m venv mytask-env

After entering this command, we have successfully created a virtual environment i.e., mytask-env.

In the next step, we will activate that virtual environment with the below command.

> mytask-env\Scripts\activate

With this step, we have successfully created and activated a virtual environment in our Django project.

Also, check: Python Django vs Flask – Key Differences

Step-2: Installing Django & Summernote editor in our virtual environment

We have created a virtual environment, now we are going to install Django in our virtual environment using the pip command.

> pip install django

Note: Make sure that you have activated virtual environment while running commands . We can use below command to activate our virtual environment

> venv\Scripts\activate.bat

In the next step, we need to install the Summernote text editor and for that, we will install the django-summernote module in our virtual environment by following the command mentioned below.

> pip install django-summernote

Step-3: Setup a Django Project in Python

After installing Django and Summernote, in the next steps, we will setup our Django project.

READ:  How to Convert Pandas Dataframe to Tensor Dataset

Creating Django Project

To create a Django Project in Python, run the following command.

> django-admin startproject MyTask

Using this command, we have created a Django project named MyTask. This will create default files and a directory in the project files.

Moving to the project directory

To work within our project, we need to move to the project directory using the following command.

> cd MyTask

Creating an App

Within our project directory, we will create a Django app named taskapp using the below command.

> python manage.py startapp taskapp

Till now, we have successfully created our Django application taskapp. Within this app, you will see the directories generated by default after the execution of the above command.

Open the Django Project in the VS Code

Start Visual Studio Code > Under Get Started click on the Open Folder option > Select the myTask directory.

Configuring App

To configure our app, go to settings.py under the MyTask directory then go to the INSTALLED APPS list and register ‘taskapp’ & ‘django_summernote’. An example is shown below.

INSTALLED_APPS = [
    .
    .
    .
    .
    'taskapp',
    'django_summernote',
]

URL Configuration

Now we need to add urls path in our urls.py file. This will render the path we see in views.py through a user interface. So, we will add the below code in our urls.py file.

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('taskapp.urls')),
    path('summernote/', include('django_summernote.urls')),
]

When we are done with defining urls in our urls.py, here we need to define media URLs in the context of summernote media files. So, follow the code mentioned below.

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Till this step, we are done with defining URLs and completed the basic configuration of our project.

Also, check: Difference between app and project in Django

Step-4: Creating Django Model in Python

In this step, we will create models in our Django project and for that, we need to create models.py for our application taskapp.

So, go to taskapp/models.py file and follow the codes and steps mentioned below.

from django.db import models
from django.utils import timezone
 
class Post(models.Model):
    category_name = models.CharField(max_length=250, default='basic')
    title = models.CharField(max_length=100)
    blog_post = models.TextField()
    is_active = models.IntegerField(default = 0)
    date_added = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Step-5: Registering models in admin panel

In the admin panel, we can use models to automatically build a site area that we can use to create, view, update, and delete records. So, to access this Django Admin Panel we need to create a super user and for that follow the below command in the terminal.

> python manage.py createsuperuser

After executing this command, it will ask to specify the superuser name, email, and password.

Now get back to our admin.py file given under the taskapp directory and add the following code.

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

class PostAdmin(SummernoteModelAdmin):
    summernote_fields = ('blog_post',)

admin.site.register(Post, PostAdmin)

Step-6: Create a form using Django model

So, now we will create a Django Form by using the fields we have already defined in the Post model. For this create a forms.py file in taskapp and write the following code in forms.py file.

from django_summernote.widgets import SummernoteWidget
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
   class Meta:
      model = Post
      fields = ['title', 'category_name', 'blog_post']
      widgets = {'blog_post': SummernoteWidget()}

Step-7: Rendering the Django ModelForm in Templates

After creating a form, we will render the form in our templates. Now follow the below steps to render the forms in templates:

  • Create folder templates in our application taskapp.
  • Now, we need to include the templates directory under the DIRS list in our settings.py file.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

In the next step, we will create a basic home page so, create an html file named home.html under the templates directory. Then follow the code mentioned below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Summernote Post</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}

        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step-8: Creating views and storing data to model

Next, we reached the stage where we will define the logic to fetch the data from the Django Form and store it in the Post model.

READ:  Attributeerror: Module 'tensorflow' has no attribute 'variable_scope'

For this execution, define a function-based view in the views.py file under taskapp directory. The Python code for the views.py file is given below.

from django.shortcuts import render
from django.http import HttpResponse
from .forms import PostForm

def note_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('new form is added')
    else:
        form = PostForm()
        context = {
                'form':form
                }
            
    return render(request, 'home.html', context)

In the above step, we have created a functioned-based view named note_post. with the help of this function, we will able to check the validation of our form. After the successful validation, it will store the form data in tables.

In case, validation is not successful, it will again return the form.

Step-9: Defining the URL for the view

Now we will map the views in the URL. So, go to urls.py under taskapp folder and follow the code mentioned below.

from django.urls import path
from .views import note_post

urlpatterns = [ 
    path(' ', note_post, name='note_post' ),
]

Step-10: Make Migrations

We have created models and propagated the changes that we have made in models into the database. So, we need to make the migrations and for that run the below commands in the terminal.

> python manage.py makemigrations
> python manage.py migrate

Step-11: Run the development server

In this step, we are ready to run our server where we can view our app in the browser, for this, run the following command in the terminal.

>  python manage.py runserver
How to use-Summernote Editor in Django
Home page of TaskApp in Django

We can see on the browser that our summernote editor is note editor is not integrated with the Body field.

To open our Rich text editor, we have to view it through our admin panel. Now open the http://127.0.0.1:8000/admin/ URL and use the credentials of superuser to log in to the Django admin panel.

READ:  Python Scipy Sparse Csr_matrix

Here if we open the Posts given under the TASKAPP section and click on Add Post button, we can observe the rich text editor is added for the post Body field.

Additionally, we can use this Summernote editor to insert data into the Body column for the Post.

To view this rich text editor in template form we need to integrate the summernote text editor. Here we will open the home.html and follow the below code.

<!DOCTYPE html>
<html lang="en">
<head>
    
    {{form.media}}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Summernote Post</title>
</head>
<body>
    <form method="POST">
        {% csrf_token %}
        {{form.as_p}}

        <input type="submit" value="Submit">
    </form>
</body>
</html>

In the next step, after adding the above Python code, refresh the http://127.0.0.1:8000/ page and now, we will get the Summernote Editor for the Post content form field. Here is the result.

Summernote editor in Django
TaskApp with Summernote Editor

Now, we have successfully integrated Summernote rich text editor in Django and we can use this rich text editor for creating and editing blog posts, articles, and other web content. We can also add images, videos, and format text using a variety of styles such as bold, italic, etc.

Here is an example:

Add Summernote editor in Django
Creating a post using Summernote editor

Rendering Summernote editor data in HTML templates

Now after successful integration of Summernote editor in our forms and admin panel, We are going to render the data stored by using Summernote in our HTML templates.

In the next step, we will create two more views in our views.py file

def task_list(request):
    post_list = Post.objects.all()
    return render(request, 'task_list.html', {'posts': post_list})

def task_view(request,post_id):
    post_view = Post.objects.filter(id=post_id)
    return render(request, 'task_view.html', {'post': post_view}) 

Here the task_list view redirects to the task_list.html page. And the task_view view redirects to the task_view.html page.

First, let us look at the code of the task_list.html page.

<h1>List of Posts</h1>
    <ol>
        {% for post in posts %}
        <li><a href="{% url 'task_view' post_id=post.id %}">{{ post.title }}</a></li>
        {% endfor %}
    </ol>
</body>

Next, let us look at the task_views.html page.

<head>
    {% for info in post %}
    <title>{{info.title}}</title>
</head>
<body>
    <h1 style="text-align: center;"><u>{{info.title}}</u></h1>
    {{info.blog_post | safe}}
    {% endfor %}
</body>

Now, to fetch the title and body of the forum we are going to use for loop. Although we already have the HTML tags in info. body field. But here we need to use safe flag.

After creating task_list.html and task_view.html, we are going to define the URL for each of the views. For that, follow the code mentioned below in urls.py file of our App.

from django.urls import path
from .views import note_post,task_list,task_view

urlpatterns = [  
    path('', note_post, name='note_post' ),
    path('posts/', task_list, name='task_list'),
    path('posts/<int:post_id>', task_view,  name='task_view'), 
]

Now, we are going to check the changes we have made. So run the development server using python manage.py runserver command and open the URL

In below image we can see the list of posts we have created in Summernote Editor.

Creating post in Summernote editor in Django
List of posts created using Summernote editor in Django

When we click any of the post links, It will return the post from rendering the data from task_views page.

Integrating a summernote post in Django
Creating a post using Summernote editor in Django

Conclusion

In this Python Django tutorial, we learned and did the implementation in our Django project “How we can use and integrate Summernote editor in Django“.

We have also learned how to render the data stored using the Summernote editor in Django Template.

Also, check similar posts on Python Django.