Ckeditor, a WYSIWYG rich text editor allows users to write content directly inside web pages or online applications. A Django WYSIWYG editor built upon CKEditor, you can use it as a standalone widget, or use the provided RichTextField or RichTextUploadingField on your models.
In this tutorial we will discuss:
- Installation and configuration
- django-ckeditor integration with admin
- django-ckeditor integration in your forms and views.
- Following django-ckeditor functionalities: Image upload, Youtube videos integration, GIFs integration, Code editor
Installation and Configuration.
Install django-ckeditor.
pip install django-ckeditor
Note: In this tutorial, I am using django==3.2.15 and django-ckeditor==6.0.0
Please make sure you use the same versions. I tried using django-ckeditor==6.3.2 but RichTextUploadingField field was not appearing in the admin panel. So please follow the same steps and versions.
Add ckeditor
in INSTALLED_APPS in your settings.py
# settings.py
INSTALLED_APPS = [
...
'ckeditor',
]
Then set STATIC_ROOT in your settings.py file.
# settings.py
# if you are using pathlib Path
STATIC_ROOT = BASE_DIR / 'static'
#if you are using os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then run python manage.py collectstatic
command. This command will copy the django-ckeditor static and media resources into the directory given by the STATIC_ROOT.
After running this command you will get this message in the terminal and also a folder named static/ckeditor
1383 static files copied to 'your path'.
Also, add media file settings in the settings.py file.
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Then set some ckeditor settings in your settings file
# settings.py
# CKEditor Settings
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_CONFIGS = {
'default':
{
'toolbar': 'full',
'width': 'auto',
'extraPlugins': ','.join([
'codesnippet',
]),
},
}
You can check more configurations from the documentation.
Main urls.py
Go to main_project/urls.py and add the following URL.
#urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
.....
path('admin/', admin.site.urls),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models.py
We are using RichTextUploadingField for file support.
# models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from ckeditor_uploader.fields import RichTextUploadingField
class BlogPost(models.Model):
title = models.CharField(
_("Blog Title"), max_length=250,
null=False, blank=False
)
body = RichTextUploadingField()
def __str__(self):
return self.title
Then run migrations.
Register your models in admin.py
# admin.py
from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
Then open the admin panel. You will see Ckeditor.
django-ckeditor integration in your forms and views.
# forms.py
from django import forms
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from blogs.models import BlogPost
class BlogForm(forms.ModelForm):
body = forms.CharField(widget=CKEditorUploadingWidget())
class Meta:
model = BlogPost
fields = '__all__'
# views.py
from django.urls import reverse
from django.views.generic.edit import CreateView
from django.contrib.messages.views import SuccessMessageMixin
from .forms import BlogForm
from .models import BlogPost
class AddBlog(SuccessMessageMixin, CreateView):
form_class = BlogForm
model = BlogPost
template_name = "blogs/add_blogs.html"
success_message = "Added Succesfully"
def get_success_url(self):
return reverse('add_blogs')
# app/urls.py
from django.urls import path
from .views import AddBlog
urlpatterns = [
path('create/', AddBlog.as_view(), name='add_blogs'),
]
Then add template blogs/add_blogs.html
<!-- blogs/add_blogs.html-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<title>CKEditor</title>
</head>
<body>
<!-- for messages -->
<div class="container">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
{{message}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
</div>
<!-- form -->
<div class="container mt-5">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media}}
{% for field in form %}
<div class="form-group">
<div><label for="{{ field.id_for_label }}" class="text-dark">{{ field.label }}: </label></div>
{{ field }}
</div>
{% endfor %}
<div class="row justify-content-center">
<input type="submit" class="btn btn-info btn-lg" value="Create" />
</div>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
</body>
</html>
Go to http://127.0.0.1:8000/blogs/create/. You will see following page.
django-ckeditor Functionalities.
How to upload an image in django-ckeditor.
If you are using RichTextField
field instead of RichTextUploadingField.
Then you won't see Upload option in image upload.
How to add Code snippet in django-ckeditor.
You can add code snippets using the option available on the right side of the insert image.
How to add Youtube videos or GIFs in django-ckeditor.
You can also use youtube videos or GIFs in CKEditor using the Iframe option.
There is another option to add iframes (youtube iframes or any). You can add using the Source button which is the first button in the editor toolbar.
How can I view/add the HTML (source code) of this blog post?
Go to the Source button which is the first button in the editor toolbar. You can add and view HTML using the Source button.
USE CASE: For example, you have an HTML of your blog and you want to copy that to your ckeditor. Then you can add that HTML easily by pressing the Source button.
If you are facing any problem related to described feature then please watch this video.
Source code is available here.
If you like this post then show some love by clapping. You can also support us by buying me a coffee. If you want more content then don't forget to subscribe to our new letter.
Related
How to add CKEditor 5 in django.
I would greatly appreciate it if you subscribe to my YouTube channel, Let's Code More