How to add a text editor field in Django?


Many online exam taking websites use text editors for text entries. image uploading, etc. Quill text editor is very popular and it also provides a model field to directly store in database. So, you don't need to configure anything extra to save its data in database.

In this article, we will see how to make a text editor field in Django.

First of all, create a Django project and an app. Do some basic settings like including urls of app. Create a media folder at the same level of project and app.

In settings.py, add −

INSTALLED_APPS = [ 'myapp.apps.MyappConfig', #django app
' django_quill' #module name]
.
.
.
.
..
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Install the django_quill package −

pip install django_quill

Example

n app's urls.py, add the following −

from django.urls import path
from . import views
urlpatterns = [
   path('', views.home,name="home"),
]
urlpatterns += static(settings.MEDIA_URL,
                           document_root=settings.MEDIA_ROOT)

Here we simply set our main view on url and media folder url.

Now, create a templates folder in app's directory and create home.html file in it. Add the following lines in home.html

<!DOCTYPE html>
<html>
   <head>
   {{ form.media }}
      {% include 'django_quill/media.html' %}
      <title>
         TUT
      </title>
   </head>
   <body>
      <form role="form" method="POST">
         <legend>Form Title</legend>
         {% csrf_token %}
      {{form}}
         <button type="submit" class="btn btnprimary">Submit</button>
      </form>
</html>

Here we rendered our form that we send from our backend.

In views.py, add the following lines −

from django.shortcuts import render
from django import forms
from .models import another_model

class NewForm(forms.ModelForm):
   class Meta:
      model=another_model
      fields="__all__"

def home(request):
   if request.method =="POST":
      form=NewForm(request.POST)
      if form.is_valid():
         form.save()
   form=NewForm()
   return render(request,'home.html',{"form":form})

Here we created a form and then we rendered it using home view. For handling POST view, we validated the form data and then saved it.

In models.py, add the following lines −

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

class another_model(models.Model):
   name = models.CharField(max_length=200)
   place = models.CharField(max_length=100)
   animal = models.CharField(max_length=100)
   thing = models.CharField(max_length=100)
   content = QuillField(blank=True)

Here we created a model and in it, we created the text editor field, which will store the data of our text editor.

Output

Updated on: 26-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements