Integrating Markdown for Enhanced Rich Content in Django Projects
Written on
Chapter 1: Introduction to Markdown in Django
When dealing with multiline content in Django, the default template filter linebreaks can help, but often we desire a more refined presentation than just plain text. This is where employing a Markdown package becomes beneficial.
Creating a New Project
To kick things off, initiate a new Django project and an app for Markdown usage:
django-admin startproject project
django-admin startapp markdown_example
Next, register your app in the settings file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'markdown_example.apps.MarkdownExampleConfig',
]
Installing Necessary Packages
Install the required packages using pip:
pip install markdown
pip install "psycopg[binary]"
Creating a Custom Template Filter
Within the templatetags folder of your app, create a filter that allows for Markdown usage:
from django import template
from django.utils.safestring import mark_safe
import markdown
register = template.Library()
@register.filter(name="markdown")
def markdown_format(text):
return mark_safe(markdown.markdown(text))
Defining the Model
Your model should include a title and a text field for extended descriptions:
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
Running Migrations
Execute the following commands to apply your migrations:
python manage.py makemigrations
python manage.py migrate
For reference, here’s how you can configure your PostgreSQL settings in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': '127.0.0.1',
'NAME': 'markdown',
'USER': 'postgres',
'PORT': '5432',
'PASSWORD': '123456',
}
}
Admin Configuration
To manage your Todo items from the admin panel:
from django.contrib import admin
from .models import Todo
@admin.register(Todo)
class TodoAdmin(admin.ModelAdmin):
pass
Creating a Superuser
Generate a superuser to manage your Todo items:
python manage.py createsuperuser
Starting the Application
Run the server to view your application:
python manage.py runserver
You can create sample Markdown content to test how headings and Python code are rendered.
Creating the View
To display all Todo items, define a view and pass the data to the index.html template:
from django.shortcuts import render
from .models import Todo
def index(request):
todos = Todo.objects.all()
return render(request, "index.html", {"todos": todos})
Updating URLs
In your urls.py, register the view as follows:
from django.contrib import admin
from django.urls import path
from markdown_example import views # new
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index), # new
]
Using the Markdown Filter in Templates
To utilize the Markdown filter, make sure to load the markdown_tags file in your template:
{% load markdown_tags %}
<h1>Markdown</h1>
{% for todo in todos %}
<h2>{{ todo.title }}</h2>
<div>{{ todo.description|markdown }}</div>
{% endfor %}
Improving Markdown Display
If the code isn't displaying correctly, you can enhance it with some CSS. Add this CSS to your HTML file:
code {
display: block;
white-space: pre-wrap;
}
Now everything should render properly.
Markdown in Action
Thank you for reading! Your interest in Markdown integration in Django is appreciated. Should you have any feedback or questions, feel free to reach out.
In Plain English 🚀
We appreciate your engagement with our community! Don't forget to follow us for more insights and updates:
- X | LinkedIn | YouTube | Discord | Newsletter
For additional content, explore our other platforms: Stackademic | CoFeed | Venture | Cubed. More information available at PlainEnglish.io.
Chapter 2: Adding a Rich Text Editor to Your Django Blog
To enhance your Django blog with a rich text editor, check out the video tutorial below. It covers the steps to integrate a functional rich text editor seamlessly into your Django application.
Chapter 3: Django Markdown Tutorial
Explore a comprehensive tutorial on utilizing Markdown in a simple blog application. This video provides a practical example of implementing Markdown in a Django/Python project.