Integrating GrapesJS with Django

GrapesJS is a robust, open-source web builder framework that enables users to create web pages visually. Integrating with Django allows developers to build and manage web pages dynamically. This article will guide you through integrating GrapesJS with Django in a simple, human-readable manner.

1) Prerequisites

Before we start, ensure you have the following installed:

  • Python (>=3.6) – Required for running Django applications.
  • Django (>=3.x) – A high-level Python web framework.
  • Basic knowledge of Django – Familiarity with views, models, and templates.
  • A working Django project – If you don’t have one, we will guide you on setting it up.
  • Static files handling – Understanding how Django serves static files.
  • Basic HTML, CSS, and JavaScript – Necessary to work with GrapesJS.

2) Render GrapesJS

To render GrapesJS within Django, follow these steps:

2.1) Step 1: Install and Set Up Django

First, ensure Django is installed on your system. If Django is not installed, you can install it using the following command:

pip install django

Once installed, create a new Django project and navigate into it:

django-admin startproject myproject

cd myproject

python manage.py startapp builder

 

Now, add the new builder app to Django’s INSTALLED_APPS in settings.py:

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

 

This ensures that Django recognizes the builder app, which will be responsible for handling GrapesJS integration.

2.2) Step 2: Set Up Static Files

Django requires proper static file configuration to serve CSS and JavaScript files. To configure static file handling, modify settings.py as follows:

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

Next, create a static directory in your project root to store static assets:

mkdir static

This directory will store JavaScript and CSS files required by GrapesJS.

2.3) Step 3: Download and Include GrapesJS

To integrate GrapesJS, download its necessary files and place them in the static folder. Run the following commands:

mkdir -p static/grapesjs
cd static/grapesjs
wget https://unpkg.com/grapesjs/dist/grapes.min.js
wget https://unpkg.com/grapesjs/dist/css/grapes.min.css

This downloads the required JavaScript and CSS files, making them available for use in your Django templates.

2.4) Step 4: Create the Builder Template

Now, create a new template that will render the GrapesJS editor. Inside the builder/templates/builder/ directory, create a file named editor.html and include the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GrapesJS Editor</title>
    <link rel="stylesheet" href="/static/grapesjs/grapes.min.css">
</head>
<body>
    <div id="gjs"></div>
    <script src="/static/grapesjs/grapes.min.js"></script>
    <script>
        var editor = grapesjs.init({
            container: '#gjs',
            height: '100vh',
            fromElement: true
        });
    </script>
</body>
</html>

This file includes GrapesJS and initializes the editor inside a div with an ID of gjs.

2.5) Step 5: Set Up the View and URL

To render the GrapesJS editor page, define a Django view. Open builder/views.py and add the following function:

from django.shortcuts import render
def editor(request):
    return render(request, 'builder/editor.html')

 

Next, register this view in the urls.py of the builder app:

from django.urls import path
from .views import editor
urlpatterns = [
    path('editor/', editor, name='editor'),
]

Then, include this builder app URL configuration in your project’s main urls.py:

from django.urls import include
urlpatterns += [path('builder/', include('builder.urls'))]

2.6) Step 6: Test the View

Start the Django development server and visit http://127.0.0.1:8000/builder/editor/ to see the GrapesJS editor in action:

python manage.py runserver

 

3) Storing GrapesJS Content

To save the content generated by GrapesJS and retrieve it later, follow these steps:

3.1) Step 1: Create a Model to Store the Pages

Define a database model to store page data in models.py:

from django.db import models
class Page(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

Run migrations to apply the model changes:

python manage.py makemigrations builder
python manage.py migrate

 

Looking For a GrapesJS development Team?

Share the details of your request, and we will provide you with a full-cycle team under one roof.

Get an Estimate

 

This will create a database table to store page titles and HTML content.

3.2) Step 2: Add a Preview View

To preview saved pages, modify views.py to retrieve stored content:

from django.shortcuts import get_object_or_404
from .models import Page

def preview(request, page_id):\
    page = get_object_or_404(Page, id=page_id)
    return render(request, 'builder/preview.html', {'content': page.content})

Create a template preview.html to display the stored HTML content:

<!DOCTYPE html>
<html>
<head>
    <title>Preview</title>
</head>
<body>
    {{ content|safe }}
</body>
</html>

This allows users to preview previously saved pages.

3.3) Step 3: Change the Builder View to Be Per Page

Modify editor view to allow editing specific pages:

def editor(request, page_id=None):
    page = None if page_id is None else Page.objects.get(id=page_id)
    return render(request, 'builder/editor.html', {'page': page})

3.4) Step 4: Save/Load Views

Modify editor.html to handle saving data via AJAX:

<button id="save-btn">Save</button>
<script>
    document.getElementById('save-btn').addEventListener('click', function() {
        fetch('/builder/save/', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}'},
            body: JSON.stringify({
                title: "My Page",
                content: editor.getHtml()
            })
        });
    });
</script>

4) Wrapping Up

You have now successfully integrated GrapesJS with Django, allowing users to build, store, and preview pages dynamically. This guide provides a solid foundation to enhance your Django projects with a powerful visual page builder. You can extend it further by implementing user authentication, role-based access control, and exporting pages as static HTML.

Share this article

Leave a comment

Related Posts