Why Is WYSIWYG Editor a Must-Have for Adding Rich Content to Django?

0
1322
WYSIWYG Editor
Credit: airship.com

Content builds relationships. Relationships are built on trust. Trust drives revenue.”  —Andrew Davis.

Truly well said 👏

Content is king. It not only builds relationships but also drives revenue, and those are what every organization needs most today. In a nutshell, content plays a vital role, and it should always be structured to look authentic and engaging and drive profit.

With the understanding of the importance of content, it’s time to jump on the most anticipated topic: adding rich content to Django (web framework).

For many of you, this might be the most daunting job you have ever done. The difficulty of understanding Django is the top reason for this because, before working with Django, you must have knowledge about Python.

💡 However, we’ve got a solution for you.

It’s WYSIWYG Editor!

You might have seen the WYSIWYG acronym multiple times on the web in different blogs but may not have gotten a chance to understand why it’s an absolute must-have to add content to Django.

Read this blog to know everything there is about this trillion-dollar question.

What Is a WYSIWYG Editor?

“What you see is what you get” is the meaning of the tech acronym for a WYSIWYG editor.

Do you get what it means?

A WYSIWYG content editor tool lets you edit the content, whether text or graphics, and reflects it immediately on the screen in the final form.

One thing you may be surprised to learn is that it doesn’t require any additional coding effort.

Sounds interesting, doesn’t it? It is. 

So whenever you edit something in a WYSIWYG editor, it will quickly appear as the final output with no manual coding or unnecessary implementation.

The best example of a WYSIWYG editor is Microsoft Word. Assume you have a blank sheet and some formatting tools to add and format words, tables, photos, and so on. When you print the document, you get exactly what you see on the screen. That’s what the WYSIWYG content editor does on the web.

One important question that may be going through your mind is why a WYSIWYG editor is the perfect choice for adding content to Django rather than traditional editors.

The answer is pretty simple!

Traditional plain-text editors require developers to enter descriptive code or markup to develop websites, while WYSIWYG rich-text editors don’t. Also, traditional text editors don’t give you a quick way of viewing the results of what you’re doing, while a WYSIWYG editor does.

Overall, a WYSIWYG editor makes it easier, in comparison to traditional text editors, for marketers to deliver a more enjoyable user interface without relying on developers.

Not sure whether it will work well with your requirements?

No problem!

We’ve curated a list of its top-notch benefits. Let’s have a look.

Benefits of using WYSIWYG editors

There are myriad benefits of WYSIWYG editors for individuals, businesses, and even marketers.  Let’s discuss them here.

👉 Simple and easy to use

Simplicity is the first and foremost benefit of WYSIWYG editors. As they don’t require any technical background or programming skills, you can quickly kick-start and create professional-looking websites or web pages the way you want.

👉 Eradicate developer dependency

As we just mentioned in our first benefit, without any technical knowledge, you can work on a WYSIWYG editor; you will not need to hire a developer. By downloading readily available free templates, you can have a great website, saving time and money that you would be paying to developers otherwise.

👉 No waiting time to make or reflect changes

Another notable benefit of using the WYSIWYG editor is that, whenever you want to change something on your website, you can make the changes quickly by yourself and see them immediately without any waiting time. Everything will be done in a few clicks, from adding content to modifying, deleting, or optimizing it.

👉 Enhance customer satisfaction

If you have a dynamic website, like a blog or an article directory, where people can contribute content, the WYSIWYG editor is bliss for you. Users can utilize the editor to style their content in the way they want and add the preferable tone and accent to their write-ups, which was earlier impossible for writers who were inexperienced with HTML code.

👉 Accurate

Yet another tremendous benefit of WYSIWYG editors is that you don’t have to perform tag validation as you usually do in traditional editors. With complete accuracy, they will provide you with the best results if you don’t make any mistakes in designing by yourself.

These are a few of the best benefits of WYSIWYG editors that show how they are revolutionizing the way content is edited.

Now, it’s time to shed light on one of the best WYSIWYG editors, called Froala Editor, which is considered the best choice for adding content to Django.

What makes it perfect for this job? Have you ever looked into it? Let’s find out the answer together.

Why choose Froala?

✨ Because Froala is a beautiful JavaScript web editor that’s easy to integrate for developers ✨

Its simple design and ultra-high-performance features make it a top-notch choice for adding rich content to Django. With more than 170 Bootstrap-based responsive design blocks ready to use for building robust and scalable websites, it has been used by thousands of companies in around 100 countries.

If you’re looking for a text editor that makes keeping or cleaning formatting when pasting rich content from Microsoft Word and Excel a simple job, this rich-text editor has no rival.

To use Froala’s WYSIWYG HTML text editor, you must have installed Django in your system.

However, if you have not installed Django, the step-by-step guide below will help you out.

  • Install Python
  • Install Django
  • Configure WYSIWYG Editor in Django

Let’s get started 🚀🚀🚀

Step 1: Install Python

Being a Python web framework, Django requires Python. So, to install Django, you must first have installed Python.

There might be time for you to dive deeper and deeper into the installations.

But these are essentials.

👉 Always ensure you install the latest Python version either by visiting the official Python site or use your operating system’s package manager.

Once you’ve installed Python on your system, you can verify whether it is successfully installed or not by typing “Python” from your shell. You will see something like this:

Python 3.x.y
[GCC 4.x] on Linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

Step 2: Set up a database

This step is important only if you want to work with a large database engine such as MariaDB, MySQL, PostgreSQL, or Oracle.

Well, you’ve completed the initial chapter of the journey. Now, it’s time to install Django, for which you installed Python.

Step 3: Install Django

You can install Django in three following ways.

👉Install an official release: This is the best method for almost every user.

👉Install the latest development version: This is the best method for enthusiasts who want the latest and greatest features and aren’t afraid of running brand new code.

👉Install a version of Django provided by your operating system distribution.

Verifying

To verify that Django can be seen by Python or has been installed successfully, type “Django” from your shell, just like you did in the case of Python above. After that, at the Python prompt, try to import Django with the below command.

>>> import django
>>> print(django.get_version())
4.0

That’s it!

This way, you can install another version of Django as well.

Now, it’s high time to discuss how to make the most of WYSIWYG Editor in Django for adding content. Thus, we will again provide a brief configuration guide because it all starts with the configuration.

Configure WYSIWYG Editor in Django

Installation

Install the package with the below command.

pip install django-froala-editor

If not updated in PyPI, use this command.

pip install https://github.com/froala/django-froala-editor/archive/master.zip

OR

Add the directory froala_editor from this repo to your Python path.

  • Add froala_editor to INSTALLED_APPS in settings.py.
  • Add the following line to URL patterns in your application’s urls.py.
  url(r’^froala_editor/’, include(‘froala_editor.urls’)),

Note: You can skip this URL inclusion if you don’t want to upload an image or file inside the WYSIWYG editor.

Usage

To use django-froala-editor, run the following command.

from django.db import models
from froala_editor.fields import FroalaField

class Page(models.Model):
  content = FroalaField()

You may not have known that FroalaField uses froala_editor.widgets.FroalaEditor as its widget.

You can directly use this widget with any of your forms.py:

from django import forms
from froala_editor.widgets import FroalaEditor

class PageForm(forms.ModelForm):
  content = forms.CharField(widget=FroalaEditor)

Usage outside admin

If you are using Django outside of its own admin, you must manually include the media files in the template. Inside the <head> section or before the form is rendered, include:

{{ form.media }}

Upload images

Now, when you’ve configured the WYSIWYG HTML editor, move to the “upload rich content” process. In this article, we’re giving you an example of uploading images as rich content.

The image-uploading process consists of three main steps that you must follow to ensure successful uploading.

❖     Initialize the JavaScript editor

❖     Receive the uploaded image and store it

❖     Return the path to the uploaded image

Let’s find out how you can easily upload images in a few clicks.

Step 1: Initialize the JavaScript editor

Make sure you’ve set the rich-text editor’s imageUploadURL option as the URL from where you want to have the images uploaded.

👉 One thing you must like about the WYSIWYG HTML editor is that you can set other options related to the way the images are being uploaded and what data your server receives.

For example, you can set imageAllowedTypes, imageUploadParam, imageUploadParams, imageMaxSize, and imageUploadMethod by running the following command.

<script>
  new FroalaEditor(‘.selector’, {
    // Set the image upload URL.
    imageUploadURL: ‘/upload_image’
  })
</script>
Step 2: Receive the uploaded image and store it

The server implementation is accountable for receiving the request and effectively handling it.

In Python, the uploaded picture is included in your application’s request. It is, however, advisable to wrap the request object in an adapter.

The Python SDK comes with three adapters: Django, Pyramid, and Flask. And the best thing to note down is that you can also make your own by extending the BaseAdapter class.  Below, we’ve explained the Django Adapter example.

from froala_editor import BaseAdapter

class DjangoAdapter(BaseAdapter):
“””
Django Adapter: Check BaseAdapter to see what methods description.
“””

def checkFile(self, fieldname):
  If fieldname not in self.request.FILES:
    raise Exception(“File does not exist.”)

def getFilename(self, fieldname):
  self.checkFile(fieldname)
  return self.request.FILES[fieldname].name

def getMimetype(self, fieldname):
  self.checkFile(fieldname)
  return self.request.FILES[fieldname].content_type

def saveFile(self, fieldname, fullNamePath):
  self.checkFile(fieldname)

  with open(fullNamePath, ‘wb+’) as destination:
    for chunk in self.request.FILES[fieldname].chunks():
        destination.write(chunk)

Based on your choice, you can opt for any of three methods from BaseAdapter. The Python editor SDK is designed to detect the uploaded image automatically, so you have to specify the path to store it.

Note: The path of the image must be related to the root of your application, such as:

response = Image.upload(CustomAdapter(request), ‘/public/’)
Step 3: Return the path to the uploaded image

The SDK generates an ImageResponse object containing the absolute path of the uploaded image if the save action is successful, so your server needs only to return it to the client.

# Return a json. You can use json.dumps to transform the response dictionary into a json string.
json.dumps(response)

Great! You’ve successfully uploaded the image as rich text to Django 💪

Amazon S3 integration

Now, when you’ve uploaded the image as rich text to Django and want to upload it to Amazon S3, you can upload it effectively because the Froala WYSIWYG Editor allows you to integrate Amazon S3 to Django.

We’ll explain how to upload images to S3.

Let’s get started!

Upload Images

  • Type: Object
  • Default: false
  • Plugin: min.js

To get started, the process sets the options for image upload to S3.

All the fields explained in the below example are required. Make sure that you have enabled CORS (cross-origin resource sharing) on Amazon 👇

Here is the code example you need to follow to upload the images.

new FroalaEditor(‘.selector’, {
  imageUploadToS3: {
    bucket: ‘editor’,
    // Your bucket region.
    region: ‘s3-us-east-1’,
    keyStart: ‘uploads/’,
    params: {
      acl: ‘public-read’, // ACL according to Amazon Documentation.
      AWSAccessKeyId: ‘ACCESS_KEY’, // Access Key from Amazon.
      policy: ‘POLICY_STRING’, // Policy string computed in the backend.
      signature: ”, // Signature computed in the backend.

      // If you are using Amazon Signature V4, the following should be used instead.
      // “X-Amz-Credential”: “…”,
      // “X-Amz-Algorithm”: “AWS4-HMAC-SHA256”,
      // “X-Amz-Date”: “…”,
      // Policy: “…”, //
      // “X-Amz-Signature”: “”, // computed in backend
    }
  }
});

 

This way, you can upload anything to Amazon S3, such as video, files, and themes. Below, we’ve also explained code examples. Have a look.

Upload video

  • Type: Object
  • Default: false
  • Plugin: video.min.js

Code example:

new FroalaEditor(‘.selector’, {
  videoUploadToS3: {
    bucket: ‘editor’,
    // Your bucket region.
    region: ‘s3-us-east-1’,
    keyStart: ‘uploads/’,
    params: {
      acl: ‘public-read’, // ACL according to Amazon Documentation.
      AWSAccessKeyId: ‘ACCESS_KEY’, // Access Key from Amazon.
      policy: ‘POLICY_STRING’, // Policy string computed in the backend.
      signature: ”, // Signature computed in the backend.

      // If you are using Amazon Signature V4, the following should be used instead.
      // “X-Amz-Credential”: “…”,
      // “X-Amz-Algorithm”: “AWS4-HMAC-SHA256”,
      // “X-Amz-Date”: “…”,
      // Policy: “…”, //
      // “X-Amz-Signature”: “”, // computed in backend
    }
  }
});

Upload files

  • Type: Object
  • Default: false
  • Plugin: file.min.js

Code example:

new FroalaEditor(‘.selector’, {
  fileUploadToS3: {
    bucket: ‘editor’,
    region: ‘s3’,
    keyStart: ‘uploads/’,
    params: {
      acl: ‘public-read’, // ACL according to Amazon Documentation.
      AWSAccessKeyId: ‘ACCESS_KEY’, // Access Key from Amazon.
      policy: ‘POLICY_STRING’, // Policy string computed in the backend.
      signature: ”, // Signature computed in the backend.

      // If you are using Amazon Signature V4, the following should be used instead.
      // “X-Amz-Credential”: “…”,
      // “X-Amz-Algorithm”: “AWS4-HMAC-SHA256”,
      // “X-Amz-Date”: “…”,
      // Policy: “…”, //
      // “X-Amz-Signature”: “”, // computed in backend
    }
  }
});

Wrap Up

Wrapping up this article, we only want to say…

You’ll find several good editors to add content to Django, but Froala WYSIWYG Editor stands out.

Its awe-inspiring features and benefits have made creating websites and adding content less intimidating and painless than they were thought to be. With no technical expertise, you can configure it quickly and start working on it. Trusted by millions of users and thousands of companies, it is climbing its ladder of success quickly.

If you find the information covered in this write-up interesting, share your views and opinions. However, if you’ve tried adding rich content to Django using any WYSIWYG editor, do share your experience with us.

We’d love to hear from you!