How to Get HTML Code from Rich Text in Python Django

In this tutorial, we will discuss, how to get HTML code from rich text in Python Django.

We will develop an application using Django where we will use a rich text editor as CKEditor. And when a user types any rich text in the editor, we will get the corresponding HTML code.

You can see below the image:

Get Html code from rich text in Python Django
Get Html code from rich text in Python Django

Get HTML Code from Rich Text in Python Django

Here we will develop the application using python Django.

  • First, we will develop an application using Python Django
  • Integrating the CKEditor into the application
  • Add bootstrap to design the application including button colors
  • Using JavaScript to get HTML code from Rich text in Python Django and displaying it in a textbox.

Here are the steps we need to follow to build this application.

Step 1: Develop the Django Application

To develop the Django application, first, we need to create and activate a virtual environment.

To create a virtual environment, first of all, create a folder or directory (if not exists before). Then open the terminal or command prompt and run the below command which will create a virtual environment name “text-env”.

> python -m venv text-env

Once the virtual environment got created, run the below command to activate the virtual environment (virtualenv).

> text-env\Scripts\activate

Next, we need to install Django and CKEditor in our virtual environment and we will do that using the pip command.

pip install django

In the next step, we need to install the CKEditor text editor. For that, we will install the Django-CKEditor module in our virtual environment by following the command mentioned below.

pip install django-ckeditor

Setup a Django Project in Python

READ:  How to Create Countdown Timer using Python Tkinter (Step by Step)

We have installed Django and CKEditor, in the next steps, we will see how to set up our Django project.

Creating a Project

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

> django-admin startproject Texttohtml

Using this command, we have created a Django project named Texttohtml. 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 Texttohtml

Creating an App

We will create a Django app named HtmlEditor within our project directory using the below command.

> python manage.py startapp HtmlEditor

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

Recommendation: Difference between app and project in Django

Open the Django Project in the VS Code

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

text to html converter in Django
Folders and Directories in the Django app

Register the app and CKEditor in settings.py

We need to register our application HtmlEditor and CKEditor in the installed app section of the settings.py file. Follow the code mentioned below to register the app and CKEditor.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HtmlEditor',
    'ckeditor',
]

Creating models in the app

Now, we will create models in the models.py file in the HtmlEditor app. To create models go through the below code.

from django.db import models

from ckeditor.fields import RichTextField

class Post(models.Model):
    body=RichTextField(blank=True,null=True)

Create forms in the HtmlEditor application.

READ:  Python Scipy Sparse Csr_matrix

After creating models we need to create forms for our HtmlEditor app. For that follow the code mentioned below in forms.py file.

from django import forms
from .models import Post
from ckeditor.widgets import CKEditorWidget


class PostForm(forms.ModelForm):
    body=forms.CharField(widget=CKEditorWidget(),label="Text Editor")
    class Meta:
        model=Post
        fields=('body',)

Creating views in the HtmlEditor application

Now, in this step, we will create views in our app. For that, go to the views.py file and follow the code mentioned below.

from django.shortcuts import render
from .models import Post
from .forms import PostForm

def home(request):
    form=PostForm()
    return render(request,'HtmlEditor/home.html',{'form':form})

Read How to create a Music Player application using Django

Step 2: Create templates and integrate CKEditor into the app

We are going to create a template name home.html in our HtmlEditor app. To create a template go to the HtmlEditor app and create a new folder named templates again create a folder named HtmlEditor within templates and create a home.html file in the HtmlEditor app.

HtmlEditor>templates>HtmlEditor>home.html

Get HTML code from rich text Python Django
Creating templates in our app

Now, to create a home page where we will render our app, We have used bootstrap to make our app more dynamic. Follow the below code in the home.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RichtexttoHtml</title>


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" >


</head>
<style>
    #cke_id_body{
        width:inherit!important;
    }
    .htmleditor p{
        font-weight: 900;
        font-size: 20px;
    }
    .texteditor p label{
        font-weight: 800;
        font-size: 18px;
    }
    #htmldata{
        font-weight: 600;
    }
</style>
<body>
   

    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                <div class="texteditor">
                        {{form.media}}
                        {{form.as_p}}
                </div>
                <input type="submit" class="btn btn-info" onclick="get_html_code()">
            </div>
            <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                <div class="htmleditor">
                    <p>HTML code</p>
                   <div class="form-group">
                    <textarea class="form-control " rows="16" id='htmldata'>
                    </textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>

Read: How to use Quill Editor in Django?

READ:  How to use Tkinter Filedialog in Python [3 Examples]

Step 3: Use a Javascript function to get HTML code

In this step, we will use the Javascript function named get_html_code to get HTML code from the rich text. For that follow the mentioned code below </html> tag in home.html file.

<script>
    function get_html_code(){
        var x = CKEDITOR.instances['id_body'].getData();
        var y=document.getElementById('htmldata');
        y.innerHTML=x;
    }
</script>

Creating URLs

Now, we will create a URL path for all the views in the urls.py file of our project HTML text.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name='home'),
]

Step 4: Run the development server

We are done with all the necessary configurations of our application and now we are ready to run our app on the server where we can view the app. To run the development server we will use the runserver command.

>  python manage.py runserver

Now the URL link  http://127.0.0.1:8000/ page will redirect you to the server where we will see our application.

Html to text converter Python Django application
Get HTML Code from Rich Text in Python Django

Also, check: How to use Summernote editor in Django?

Conclusion

In this Python Django tutorial, we have learned how to create an app to get HTML code from rich text in Python Django with help of forms and model fields.

We have also learned how to integrate and use CKEditor in our application. Along with that we also learned about SMTP server settings to generate a token. Now You can simply use this app to get HTML code from rich text.

You may also like the following Django tutorials: