Building A Blog Website With Django Part 5

Before doing this tutorial, make sure you finish 

part one Creating Django Project
part two Creating Super User and Backend Dashboard access
part three ORM, Backend to CRUD Post, and Category.
part four, creating working Front End via templates and Views.

Now we want to make the post body input form as a rich text editor. For this reason we will need to install Tiny-Mce plugin.

Open your terminal command prompt and make sure you are in folder “myblog”. To change directory use “cd your_target_directory”. Then make sure you are activate your virtual environment.

Now, still in “myblog” folder, run “code .” to open your visual studio code.

Create a file named “forms.py” inside folder “myblog/blog/”.

Write the code for “myblog/blog/forms.py”.

from django import forms 
from tinymce import TinyMCE 
from .models import Post


class TinyMCEWidget(TinyMCE): 
	def use_required_attribute(self, *args): 
		return False


class PostForm(forms.ModelForm): 
	content = forms.CharField( 
		widget=TinyMCEWidget( 
			attrs={'required': False, 'cols': 30, 'rows': 10} 
		) 
	) 
	class Meta: 
		model = Post
		fields = '__all__'

Open file “myblog/blog/models.py” and modifies it. If you notice we import the HTMLField from tiny-mce and change the line on body input inside Post class .

from django.db import models
from tinymce.models import HTMLField  

class Category(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        verbose_name_plural = "categories"

    def __str__(self):
        return self.name
    
class Post(models.Model):
    title = models.CharField(max_length=255)
    body = HTMLField()  
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified_on = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField("Category", related_name="posts")

    def __str__(self):
        return self.title    

Open file “myblog/blogproject/settings.py” and add “tinymce” on INSTALLED_APPS array.

Still in file “myblog/blogproject/settings.py”, adding these texts on the bottom of file.

TINYMCE_DEFAULT_CONFIG = {
    'cleanup_on_startup': True,
    'custom_undo_redo_levels': 20,
    'selector': 'textarea',
    'theme': 'silver',
    'plugins': '''
            textcolor save link image media preview codesample contextmenu
            table code lists fullscreen  insertdatetime  nonbreaking
            contextmenu directionality searchreplace wordcount visualblocks
            visualchars code fullscreen autolink lists  charmap print  hr
            anchor pagebreak
            ''',
    'toolbar1': '''
            fullscreen preview bold italic underline | fontselect,
            fontsizeselect  | forecolor backcolor | alignleft alignright |
            aligncenter alignjustify | indent outdent | bullist numlist table |
            | link image media | codesample |
            ''',
    'toolbar2': '''
            visualblocks visualchars |
            charmap hr pagebreak nonbreaking anchor |  code |
            ''',
    'contextmenu': 'formats | link image',
    'menubar': True,
    'statusbar': True,
}

Open file “myblog/blog/templates/blog_details.html”. You will change on the way post body displayed on the website.

{% extends "base.html" %}

{% block page_content %}

<div class="container-md my-5">

{% block post %}
<article class="blog-post">
    <h2 class="blog-post-title mb-1">{{ post.title }}</h2>
    <p class="blog-post-meta">{{ post.created_on.date }}</p>
    {% for category in post.categories.all %}
        <small class="px-1">
            <a href="{% url 'blog_category' category.name %}"> {{ category.name }} </a>
        </small>
    {% endfor %}
    <div class="post-body my-4">
        {% autoescape off %}
        {{ post.body | safe }}
        {% endautoescape %}
    </div>
</article>
{% endblock post %}

</div>

{% endblock page_content %}

Make sure you save all the changes. Run the app from terminal and make sure you are in root folder “myblog”.

These our current output, Wohoo!!

Our Post form has a rich text editor and it can accepts HTML.

Now our blog details can displayed HTML

Something missing… Usually a post can have a small image as visual representation which called thumbnail. In part six we will add ability for user adding an image thumbnail.

Leave a Comment