How to use Quill Editor in Django?

In this Python Django tutorial, we will learn how to integrate another type of rich text editor into our Django project. And in this tutorial, we will explain how to use the Quill Editor in Django.

Also, we will discuss the steps to integrate the Quill Editor into the Django Admin and Django Forms using examples.

First, let us understand what is Quill Editor in Django.

Introduction to Quill Editor in Django

  • Quill Editor is a well-known rich text editor that we can integrate with Django web applications.
  • This editor allows users to modify formatted text with a number of stylistic options.
  • It offers a user-friendly interface that allows us to apply formatting options including bold, italic, underline, and bullet points.

To integrate Quill Editor in Django, we often use third-party packages or libraries, such as django-quill. This library offers a Quill Editor implementation that can be used in Django models and Django forms as well.

Step 1: Creating & activating a virtual environment for our Django Project

First, we will create a virtual environment for our Django project. Now for this, we will use the following command in our command prompt.

> python -m venv myforums-env

With the above command, we created a myforums-env. virtual environment.

After creating a virtual environment, we will use the below command to activate it.

> myforums-env\Scripts\activate

So, here we have successfully created and activated a virtual environment in Python.

Read: Python Django vs Pyramid

Step-2: Installing Django & Quill Editor in Django

In this step, we will install the Django framework using the below pip command.

Note: Please make sure you run the command with the activated virtual environment.

> pip install django

After installing Django, next, we will install Quill Editor. However, to install Quill Editor, we need to install the django-quill-editor module using the following command.

> pip install django-quill-editor

Read: Python Change Django Version

Step 3: Setup a Django Project

Once we will install Django and Quill Editor, we will use the following steps to set up our Django project.

Creating Django Project

First, we need to create a Django project and for this, we can use the following command.

> django-admin startproject MyForum

Using this command, we created the Django project with MyForum as the project name. This will create the MyForum directory will also the project files.

READ:  Python Django get admin password

Moving to the project directory

After creating the project, we need to move to the project directory using the cd command.

> cd MyForum

Creating an App for our Django Project

From the project directory, we will create our Django App using the startapp command.

> python manage.py startapp myapp

With this command, we created the Django application named myapp. Moreover, once this command is executed successfully, it will automatically generate all the application files under the myapp directory.

Open the Django Project in the VS Code

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

Configure Apps under INSTALLED_APPS

First, open the settings.py given under the myForum directory and add the myapp application and django_quill to the INSTALLED_APPS list.

INSTALLED_APPS = [
    .
    .
    .
    .
    'myapp',
    'django_quill',
]

Basic URL configuration

By default, Django has a urls.py file. This file helps to map a new app to the project directory. However, for this, add the following code in the urls.py file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))
]

Till this step, we have successfully completed the basic Django project configuration.

Step 4: Creating Django Model

To store data for our Django application, we need a model. Now, we can define models under the models.py file for each application.

So, go to the myapp/models.py file and add the following Python code.

from django.db import models
from django_quill.fields import QuillField


class Post(models.Model):
    title = models.CharField(max_length=200)
    body = QuillField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Read: Python Django vs ReactJS

Step 5: Register the model on the admin site

In this step, we need to register the Post model on the admin site so that we can access the model using Django Admin Panel.

For this task, go to the admin.py file given under the myapp directory and add the following code.

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Step 6: Creating a form using the Django model

Next, we need to create a Django Form using the same fields defined in the Post model. For this execution, we will use the following code in the myapp/forms.py file.

Note: Please note that if forms.py file is not available, please create it in your application directory.

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
   class Meta:
      model = Post
      fields = ['title', 'body']

Also, check: Python Django form validation

Step 7: Rendering the Django ModelForm in Templates

After creating a form, we will render the form in our templates. Here are the steps that we can follow for this task:

  • First, create a templates directory in your application directory (under myapp).
  • After this, go to the settings.py file and include the templates directory under the DIRS key list.
TEMPLATES = [
    {
        .
        'DIRS': ['templates'],
        .
        'OPTIONS': {
            'context_processors': [
                .,
                .,
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Next, create another file named home.html under the templates directory. Then add the following Python code to it.

<!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> My Forum Post</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}

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

Here we are loading the forms in the HTML file that we created earlier using the Post model.

READ:  Python Django MySQL CRUD

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.

For this execution, define a function-based view in the views.py file under myapp 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 create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('New Forum Successfully Added')
    else:
        form = PostForm()
        context = {
            'form':form
        }

    return render(request, 'home.html', context)

In this code, we defined a function-based view named create_post. The role of this view is to check if the form is valid or not. Moreover, if the form is validated successfully, it will store the form data in the tables.

However, if the form is not fully validated, it will again return the form.

Read: Python Django MySQL CRUD

Step 9: Defining the URL for the view

Next, we just need to map the view to an URL. So, open the myapp/urls.py file and add the following code.

from django.urls import path
from .views import create_post

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

Step 10: Make Migrations

As we created a model to store the forum data, it is important to run migrations so that changes could be reflected in our database.

So, run this command in the terminal to mark and run the migrations in Django.

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

Step 11: Creating a superuser in Django

Once our migrations are completed, we must create a superuser account to access the Admin Panel in Django. For this, run the below command in the terminal.

> python manage.py createsuperuser

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

Read: Create Contact Form with Django and SQLite

Step 12: Run the development server

Now, we are ready to run our Django application, for this, run the following command in the terminal or command prompt.

> python manage.py runserver

Once we run the above command, it will start the lightweight Django development server at port 8000 by default. To access the Django application, open this http://127.0.0.1:8000/ URL in the browser.

Initially, our Django application will look something like this:

Django App without Quill Editor
Django App without Quill Editor

On the page, we can see the rich text editor is not coming for the Body field.

Next, open the http://127.0.0.1:8000/admin/ URL, and use the superuser credentials to log in to the Django Admin Interface.

Here if we open the Posts given under the MYAPP 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 Quill editor to insert data into the Body column for the Post.

Django Admin Interface with Quill Editor
Django Admin Interface with Quill Editor

However, to add the Quill Editor to our template form, we need to add the following code to the HTML file. Here HTML file refers to home.html.

<head>

    {{form.media}}
    <title> My Forum Post</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{form.as_p}}

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

After adding the above code, refresh the http://127.0.0.1:8000/ page and now, we will get the Quill Editor for the Post content form field. Here is the result.

Quill Editor in Django Template
Quill Editor in Django Template

Now, we can use this Quill Editor to add data in a document format containing different text properties, bold, italic, underline, etc. It also allows us to insert tables and even images into the same document.

READ:  modulenotfounderror: no module named 'matplotlib'

Here is an example:

Quill Editor in Django
Quill Editor in Django

Rendering Quill Editor Data in HTML Template

Till now, we have successfully integrated the Quill Editor to our Django form and Django Admin Interface. Next, we need to understand how to load or render the data stored using Quill in our HTML template.

For this task, we will create 2 more views in our views.py file.

  1. post_list: This view will list all the blog names that are there in the Post model
  2. post_view: This view will allow viewing the exact content of the particular blog.

The code for both views is given below.

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

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

Here the post_list view is redirecting to the post_list.html page. And the post_view view is redirecting to the post_view.html page.

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

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

Here we are using for loop to get all the post titles as a list and then we are converting the title into links. This URL link will redirect to the particular forum page.

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

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

Here we are also using for loop to fetch the title and body of the forum. However, as the info.body.html field also consists of HTML tags, we need to use the safe flag with it.

Once, both the HTML files are set, we just need to define the URL for each view in Django. For this task, add the following code to the urls.py file of our Django App.

from django.urls import path
from .views import create_post, post_view, post_list

urlpatterns = [
    path('', create_post, name='create_post'),
    path('posts/', post_list, name='post_list'),
    path('posts/<int:post_id>', post_view,  name='post_view'),
]

Now, run the development server using runserver command and open the http://127.0.0.1:8000/posts/ URL in your browser.

Here all the forum titles will be listed.

Forum list in Django
Forum list in Django

Now, if we click on any of the links, it will open the post_view page containing the Forum data.

Forum view in Django app
Forum view in Django app

You may also like to read the following Python Django tutorials.

Conclusion

So, in this Python Django tutorial, we understood how to integrate Quill rich text editor into our Django Project. Here we discussed how to integrate and use the Quill Editor in Django.

In addition to this, we have also seen how to render the data stored using the Quill Editor in Django Template.