How I Created a Text-to-HTML Converter App Using Django

How would you like your text or essay quickly converted to clean HTML? That will be amazing, right?

πŸ§‘β€πŸ’» HTML, short for Hyper-Text Markup Language, is used to create web pages. Learning how to use HTML code is very important as far as web development is concerned.

However, not everyone can understand and write using HTML code. That is why it is beneficial to know how to convert text to HTML.

Therefore, in this tutorial, we will build a Django application that converts text to HTML. All you need to do is to paste your text, and you will get the content converted to clean HTML.

Project: Why Convert Text to HTML?

There are many reasons to convert your text to HTML code. They include but are not limited to the following:

  • Some online platforms only accept documents written in HTML.
  • It saves time that would otherwise be spent learning the language.

The second reason is exactly the case now in this highly competitive world where learning one programming language is no longer enough.

πŸ’‘ Recommended: What’s the Best Programming Language for Freelance Developers?

As we shall see in this tutorial, Django is a backend Python framework for creating web applications. How can you handle the front end if you have little knowledge of HTML, CSS, and JavaScript? So, learning one language is not enough.

But with the help of a text-to-html converter app, you can speed up your learning process.

Why Django?

Why use Django to create websites? Truly, web development has a steep learning curve. But with Django, the learning process is drastically reduced. Django has done all the heavy lifting for you. You only need a few lines of code to get your app up and running.

Secondly, Django has a large community supporting your web development journey. So, if you get lost, which is to be expected as a beginner (even experienced Django developers need help, too), the community is there to help you.

In this tutorial, we will seek the services of CKEditor and a little bit of JavaScript to help us convert text to HTML.

What is CKEditor?

The CKEditor is a what-you-see-is-what-you-get (WYSIWYG) rich text editor that allows users to write content directly inside web applications. It is also used to edit HTML documents in the browser.

A rich text editor is a tool that allows one to edit content without having to know HTML code. If you are a blogger, you will understand what we are discussing. WordPress, Blogger, and similar websites utilized rich text tools so anyone using their platform can start blogging immediately.

Getting Started

Creating a Django text to HTML application is one of the projects that you can learn to improve your Python skills as a Django developer. We are going to follow 5 steps to set up Django in our system using Ubuntu Terminal

  1. Create a directory and call it text_to_html. cd into the directory.
    mkdir text_to_html && cd text_to_html
  2. Create and activate a virtual environment
    python3 -m venv .venv
    source .venv/bin/activate
  3. Use pip to install Django, tzdata and django-ckeditor
    pip install django tzdata django-ckeditor
  4. Create a Django project and call it engine.
    django-admin startproject engine .
  5. Create a Django application with the name converter.
    python3 mange.py startapp converter

The dot after the engine tells Django to create the project in the current directory. Run the following code to ensure that the installation was successful.

python3 manage.py runserver

I expect you to see the above image when you open your browser and go to this URL http://127.0.0.1:8000/.

Use Control-C to quit the local server. For a brief explanation of what’s inside the project and app folders, this tutorial can help.

Create a requirements.txt file to keep a record of the packages used in this project.

pip freeze > requirements.txt

Run the ls command to ensure you have the following in your current directory.

converter engine manage.py requirements.txt

Next, open the settings.py file and let Django know we created an app. We will do this in the INSTALLED_APPS section.

nano engine/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #custom app
    'converter',
    'ckeditor',
]

Notice we also added the django_ckeditor that will be used in this project.

The Model

Our model, as usual, will inherit the models.Model class. But it will have only one field, the RichTextField from CKEditor.

nano converter/models.py
from django.db.models import Model
from ckeditor.fields import RichTextField
# Create your models here.

class Editor(Model):

    body = RichTextField(blank=True, null=True)

The Rich Text Field

The RichTextField grants us access to the rich text editor tool we explained previously. It contains many features but we will only use the default ones. You can also configure other features in the settings.py file. Doing that is beyond the scope of this tutorial. This field will remain blank when opened.

Now is the time to activate our model. Run the code below.

python3 manage.py makemigrations converter

You will get the following response from the terminal:

Migrations for 'converter':
  converter/migrations/0001_initial.py
    - Create model Editor

Although, in our case, it’s not necessary, it is always a good practice to specify which app you want to run migrations. This is important when we have several apps in our Django project. Complete the migration process by running the code below.

python3 manage.py migrate

This is the code that does the actual execution. The previous one only let Django know of changes made in the database model.

Creating a Form

Let’s now create a form that will be displayed on the web page. In your app-level folder (converter), create a file with the name forms.py.

from django.forms import ModelForm, CharField
from .models import Editor
from ckeditor.widgets import CKEditorWidget

class EditorForm(ModelForm):
    body = CharField(
        widget=CKEditorWidget(),
        label='Enter your text here...'
    )

    class Meta:
        model = Editor
        fields = '__all__'

The class inherits the ModelForm class. It is similar to our model. The CKEditorWidget is a plugin that specifies the style and layout of the WYSIWYG area. The Meta class specifies which fields in the model to display.

The Views and URLs

In views.py, we specify what we want to be displayed to the user. We want a form to be displayed to the user. So, we have to import it and use it in the function we create.

from django.shortcuts import render
from .forms import EditorForm
# Create your views here.

def index(request):
    form = EditorForm()
    return render(request, 'index.html', {'form': form})

The index.html is the file that will display the form.

Before we create the HTML file, let’s first create a urls.py file in the converter folder.

from django.urls import path
from .views import index

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

We also have to register the app-level URL in the project-level URL. Open the urls.py file in the engine folder.

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

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

We use the include() function to register the app-level folder. The empty quote means the home page URL.

Templates and Static Files

It’s now time to create the index.html file. To do so, create a template folder in the current directory.

mkdir templates

Go to settings.py file and let Django know a template folder is created. Import the os module. Then scroll down to the TEMPLATES section. In DIRS, write the following inside the empty parentheses.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this
        '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',
            ],
        },
    },
]

Once that is taken care of, go to the templates folder and create a file, index.html.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text to HTML Converter</title>
   <!-- ++++++++++++++++++++ boostrap cdn ++++++++++++++++++++++++ -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
     <link rel="stylesheet" href="{% static '/css/styles.css' %}">
     <script src="{% static '/js/script.js' %}"></script>
</head>

<body>
    <!-- ----------------------Navbar start -------------------- -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
       <h1 class="navbar-brand">Text to HTML Converter</h1>
   </nav>
    <!-- ---------------------------Navbar Ends---------------------------- -->
  <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="TextConvert()">
            </div>
            <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                <div class="htmleditor">
                    <p>HTML Editor</p>
                    <div class="form-group">
                        <textarea class="form-control " rows="16" id='htmldata'>
                    </textarea>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

I’m not going to explain everything here. We are using bootstrap to style the web page.

The {% load static %} means we import, so to speak, some files from the static folder. We are yet to create the folder. So, don’t worry about it.

Notice the syntaxes { form.media } and { form.p }. This is how we display the form.

Before explaining other important details, create a static folder and, as usual, we will let Django know of this in the settings.py file. Afterward, run the ls command. I expect to see these in your current directory.

converter  db.sqlite3  engine  manage.py  requirements.txt  static  templates

In the settings.py file, scroll down to where you will see STATIC_URL. Under it, write the following:

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Create two more folders in the static folder, and name them css and js respectively. One is for Cascading Style Sheet (CSS) and the other is for JavaScript. Having done that, create a file in the css folder and call it styles.css.

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;
    }

In the HTML file, the link tag with href='css/styles.css' is how we link the CSS file. Once you have written the script above in the file, go to the js folder, create a script.js file, and write the following:

TextConverter = () => {
    let x = CKEDITOR.instances['id_body'].getData();
    let y = document.getElementById('htmldata');
    y.innerHTML = x;
}

The script tag with src='js/script.js' is how we also link the JavaScript file. All these were made possible because of the {% load static %} Django templating language.

The JavaScript above simply creates a function that “copies” the data from the CKEditor which is now converted to an HTML code and “pastes” it to the textarea tag that has the id, htmldata.

Something, though, has to trigger this function. We did it in the input tag of the index.html file. You can see the name of the function in the tag. The tag is a button and once clicked, it executes the function.

Test the Local Server

Alright, we are done. Everything is done. We now start the local server to see what we have done so far.

Can you see the rich text tool with its default features? Can you also see how the text was converted to clean HTML?

Conclusion

This is how we come to the end of this tutorial. Check my GitHub page for the full code. No doubt, you are gradually becoming familiar with how Django works.

Django can be used to build far more complex websites than the one we designed. However, a project like this is a good start in your journey to becoming a Django developer.

βœ… Recommended: How I Created an URL Shortener App Using Django