We’ve already implemented Markdown syntax for writing articles. However, Markdown is not appropriate for comments on articles. You can’t force users to take the time to become familiar with the syntax. Comments often have features like emoticons and colored fonts, which Markdown doesn’t have.

So the rich text editor Django-ckeditor comes in handy.

Use Ckeditor in the background

Install Django-ckeditor in a virtual environment:

(env) > pip install django-ckeditor
Copy the code

Once installed, register your app in settings.py as usual:

my_blog/settings.py

...
INSTALLED_APPS = [
    ...
    
    'ckeditor'. ] .Copy the code

Now you need to modify the model. Replace TextField with django-ckeditor’s own RichTextField:

comment/models.py

...
# django-ckeditor
from ckeditor.fields import RichTextField

class Comment(models.Model):.# body = models.textField ()
    body = RichTextField()
    ...
Copy the code

Remember to migrate data after each model change:

(env) > python manage.py makemigrations
(env) > python manage.py migrate
Copy the code

To facilitate testing, modify the comment/admin.py file and register the comment module in the background:

comment/admin.py

from django.contrib import admin
from .models import Comment

admin.site.register(Comment)
Copy the code

Django-ckeditor: Django-ckeditor:

Features are complete, including fonts, sizes, colors, links and emoticons.

What if I only need partial functionality? For example, inserting flash animations is basically useless. I also don’t seem to see the ability to insert code blocks.

Ckeditor allows you to customize Settings in settings.py:

my_blog/settings.py

...
CKEDITOR_CONFIGS = {
    # django-ckeditor defaults to the default configuration
    'default': {
        # Editor width adaptive
        'width':'auto'.'height':'250px'.The # TAB key converts Spaces
        'tabSpaces': 4.# Toolbar style
        'toolbar': 'Custom'.# Toolbar button
        'toolbar_Custom': [
            # Emoticon code block
            ['Smiley'.'CodeSnippet'].# font style
            ['Bold'.'Italic'.'Underline'.'RemoveFormat'.'Blockquote'].# font color
            ['TextColor'.'BGColor'].# link
            ['Link'.'Unlink'].# list
            ['NumberedList'.'BulletedList'].Maximize #
            ['Maximize']],Add code block plugin
        'extraPlugins': ', '.join(['codesnippet']),}}Copy the code

Define the functional modules you want to use in toolbar_Custom; Features not listed are no longer displayed. The code block functionality is a plug-in that comes with the editor and needs to be specified in extraPlugins. The effect is as follows:

After editing rich text, you need to display it in the foreground interface. Rich text is similar to HTML format to save, so also in the show review code to join | safe filter, to prevent the browser to escape.

Modify the part of the code in detail.html that displays comments:

templates/article/detail.html

...

<! -- Show comments -->
<h4>There are {{comments.count}} comments</h4>
<div>
    {% for comment in comments %}
        ...
        <! -- Change here -->
        <div>{{ comment.body|safe }}</div>
    {% endfor %}
</div>.Copy the code

Enter the article details page to see the effect:

Code highlighting

Code highlighting requires the addition of the additional plug-in Prism. After downloading the Prism plugin, place the extracted Prism in env\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins. Note that env is the directory of the virtual environment you created.

All the libraries you installed before are in this env directory.

Then select a theme on Prism’s website:

  • Choose a favorite topic based on your preferences
  • Then select the language you want to highlight. If you don’t know, you can choose all
  • Check the line number plug-in
  • Finally clickDOWNLOAD CSSDownload the style

Create a new prism directory in the static directory and place the downloaded CSS files in it.

Note that static is the static file directory in the project (as in the previous section), not the static directory in the env folder.

Then reference Prism’s static file in the template file that needs code highlighting to render the code:

templates/article/detail.html

...

<script src="{% static 'ckeditor/ckeditor/plugins/prism/lib/prism/prism_patched.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'prism/prism.css' %}">.Copy the code

Add the Prism, Widget, lineutils plug-in to the configuration file. The following two editors come with you, you don’t need to download them separately, you can add them:

my_blog/settings.py

...
CKEDITOR_CONFIGS = {
    'default': {...Add prism-related plug-ins
        'extraPlugins': ', '.join(['codesnippet'.'prism'.'widget'.'lineutils']),}}Copy the code

And that’s it:

Code highlighting looks good!

Use Ckeditor in the foreground

In order to enable users to use the rich text editor in the foreground, the code needs to be changed slightly.

The first step is to pass the comment form to the article details page. So modify the article_detail view:

article/views.py

...
# Introduce comment forms
from comment.forms import CommentForm

...
# Article details
def article_detail(request, id):.# Introduce comment forms
    comment_form = CommentForm()
    context = { 
        ...
        'comment_form': comment_form,
    }
    ...
Copy the code

Then replace the body of the original detail.html comment form (i.e.

templates/article/detail.html

...

<! -- Comment -->
<form .>
{% csrf_token %}
    <div class="form-group">
        <label for="body">.</label>
        
        <! <textarea> <textarea>
        <! -- <textarea type="text" class="form-control" id="body" name="body" rows="2"></textarea> -->
        <div>
            {{ comment_form.media }}
            {{ comment_form.body }}
        </div>
        
    </div>
    <! -- Submit button -->.</form>.Copy the code

Where comment_form.media is the editor’s own rendering code and comment_form.body is the comment body field.

Look at the results:

Yes, the editor is working, but there is one small problem: the editor width doesn’t seem to be adaptive, and the large white space on the right is a waste of space. Keep trying.

Width adaptation

Start by setting the width to Auto in the configuration file, which we’ve already done.

The Ckeditor editor itself has an inline-block style that hinders the adaptive effect and needs to be removed using Jquery syntax. Add the code at the bottom of the details page:

templates/article/detail.html

<! -- Notice the wrong example! -->.<! -- Add code -->
<script>
    $(".django-ckeditor-widget").removeAttr('style');
</script>

<! -- This already exists -->
{% endblock content %}
Copy the code

The $symbol represents the Jquery statement. Find the container with class=’django-ckeditor-widget’ and delete the style attribute for that container.

There seems to be no problem, but the bugs are in the details. Note that this is a Jquery statement, so you need to load jquery.js before running it. However, when rendering the page, {% block Content %} containing the $statement is inserted in front of the jquery.js tag of the base.html template, causing the statement to fail and the console to report the error $is not defined.

An easy solution would be to move the tags introduced in jquery.js up to the top and load them before the Block template is inserted. The problem with this is that JS files are usually slow to load, which blocks subsequent code and slows down the overall page load. This approach is not adopted in this paper.

The solution is to add a special place in base.html for concatenating JavaScript scripts, named {% block script %}. Note that it must be placed after the Jquery tag:

templates/base.html

...

<body>.<! -- Existing code -->
    <script src="{% static jquery/jquery - 3.3.1. Js' %}"></script>.<! -- Add code -->
    {% block script %}{% endblock script %}
</body>
Copy the code

Then put the JS code from detail.html into this block:

templates/article/detail.html

...

{% block script %}
<script>
    $(".django-ckeditor-widget").removeAttr('style');
</script>
{% endblock script %}
Copy the code

This approach gives you flexibility in defining the order in which JS scripts are run, and makes the code look cleaner. It is recommended that all JS code be inserted in this way.

Refresh the page and the editor can adjust the width:

Post a comment with a code block and the details page will look like this:

conclusion

Blog posts and their comments can now be beautifully formatted. For those who don’t like Markdown, you can even use the rich text editor provided by Django-Cdeditor for your blog posts. I still prefer to use Markdown to write articles: efficiency is more important than good looks, and almost all major websites support Markdown, making it easy to publish on multiple platforms.

  • If you have any questions please leave a message on Doucet’s personal website and I will reply as soon as possible.
  • Or Email me a private message: [email protected]
  • Project code: Django_blog_tutorial

Thanks to Aaron Zhao’s personal blog for providing the reference for this article. Django-ckeditor also explains the Settings for uploading images to django-Ckeditor.