Skip to main content

A simple custom field for Django that can safely render Markdown and store it in the database.

Project description

django-markdownfield PyPI

A simple custom field for Django that can safely render Markdown and store it in the database.

Your text is stored in a MarkdownField. When the model is saved, django-markdownfield will parse the Markdown, render it, sanitise it with nh3, and store the result in a RenderedMarkdownField for display to end users.

django-markdownfield also bundles a minified version of the EasyMDE editor (v2.20.0) for use in admin and frontend forms.

Editor screenshot

Installation

django-markdownfield can be installed from PyPI:

pip install django-markdownfield

After installation, you need to add markdownfield to INSTALLED_APPS of your Django project's settings.

INSTALLED_APPS = [
    "markdownfield",
    ...
    "django.contrib.staticfiles",
]

Usage

Add a MarkdownField and a paired RenderedMarkdownField to your model:

from django.db import models

from markdownfield.models import MarkdownField, RenderedMarkdownField
from markdownfield.validators import VALIDATOR_STANDARD

class Page(models.Model):
    text = MarkdownField(rendered_field='text_rendered', validator=VALIDATOR_STANDARD)
    text_rendered = RenderedMarkdownField()

Displaying content

To display rendered Markdown in a template, use the RenderedMarkdownField and mark it safe:

{{ post.text_rendered | safe }}

Editor

The bundled EasyMDE editor is available in both admin and frontend forms.

Admin

The EasyMDE editor is enabled automatically in the Django admin. To disable it:

text = MarkdownField(rendered_field='text_rendered', use_admin_editor=False)

Frontend forms

The editor widget is also included automatically in frontend ModelForms. You must include the form's media in your template or the editor's JavaScript and CSS will not load:

<head>
    {{ form.media.css }}
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Save</button>
    </form>
    {{ form.media.js }}
</body>

To disable the editor in frontend forms:

text = MarkdownField(rendered_field='text_rendered', use_editor=False)

To customise the EasyMDE options, override the widget in your form. Any EasyMDE configuration option can be passed via the options dict:

from django import forms
from markdownfield.widgets import MDEWidget

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['text']
        widgets = {
            'text': MDEWidget(options={'toolbar': ['bold', 'italic', 'link']}),
        }

Configuration

All settings are optional.

Setting Default Description
SITE_URL None Your site's base URL (e.g. "https://example.com"). Used to distinguish internal from external links. Without it, all links are treated as external.
MARKDOWN_EXTENSIONS ['fenced_code'] List of Python-Markdown extensions to enable.
MARKDOWN_EXTENSION_CONFIGS {} Configuration for Markdown extensions.
MARKDOWN_LINK_BLACKLIST [] List of domains whose <a> links should be stripped from output (e.g. ['spam.example.com']). The link text is preserved; only the link itself is removed.
MARKDOWN_MARK_EXTERNAL_LINKS True When True, external links receive target="_blank" and class="external". Set to False to disable.

Validators

django-markdownfield comes with a number of validators, which are used to process and clean the output of the Markdown engine.

VALIDATOR_STANDARD

from markdownfield.validators import VALIDATOR_STANDARD

This validator strips any tags not used by standard Markdown.

VALIDATOR_CLASSY

from markdownfield.validators import VALIDATOR_CLASSY

Like VALIDATOR_STANDARD, but also allows class on links and images, and permits data-* attributes. Useful for creating styled buttons and enhanced links.

VALIDATOR_BASIC

from markdownfield.validators import VALIDATOR_BASIC

Allows only inline formatting: bold, italic, strikethrough, inline code, and links.

VALIDATOR_NULL

from markdownfield.validators import VALIDATOR_NULL

Skips sanitization entirely. Not safe for user input. Allows arbitrary HTML in Markdown input.

Creating Custom Validators

To create a custom validator, create an instance of the markdownfield.validators.Validator dataclass:

from markdownfield.validators import Validator

# allows only bold and italic text
VALIDATOR_COMMENTS = Validator(
    allowed_tags={'b', 'i', 'strong', 'em'},
    allowed_attrs={},
)

You can also extend the built-in tag and attribute sets:

from markdownfield.validators import Validator, MARKDOWN_TAGS, MARKDOWN_ATTRS

VALIDATOR_CUSTOM = Validator(
    allowed_tags=MARKDOWN_TAGS,
    allowed_attrs={
        **MARKDOWN_ATTRS,
        'img': {'src', 'alt', 'title', 'class'},
        'a': {'href', 'alt', 'title', 'name', 'class'},
    },
    generic_attribute_prefixes={'data-'},
)

To allow inline CSS but restrict which properties are permitted:

VALIDATOR_STYLED = Validator(
    allowed_tags=MARKDOWN_TAGS,
    allowed_attrs={
        **MARKDOWN_ATTRS,
        '*': {'id', 'style'},
    },
    filter_style_properties={'color', 'font-weight', 'text-align'},
)

Note: filter_style_properties has no effect unless style is included in allowed_attrs. If style is allowed but filter_style_properties is not set, all CSS properties are permitted.

To restrict permitted URL schemes (e.g. block javascript: or custom schemes):

VALIDATOR_STRICT = Validator(
    allowed_tags=MARKDOWN_TAGS,
    allowed_attrs=MARKDOWN_ATTRS,
    url_schemes={'http', 'https', 'mailto'},
)

Migrations

If you need to migrate from TextField or CharField to MarkdownField, add a RunPython step to your migration that calls save() on every existing instance so the rendered field is populated:

from django.db import migrations
import markdownfield.models


def save_text_rendered(apps, schema_editor):
    ExampleModel = apps.get_model('yourapp', 'ExampleModel')
    for examplemodel in ExampleModel.objects.all():
        examplemodel.save()


class Migration(migrations.Migration):

    dependencies = [
        ('yourapp', '000X_migrate_to_markdownfield'),
    ]

    operations = [
        migrations.AddField(
            model_name='yourapp',
            name='text_rendered',
            field=markdownfield.models.RenderedMarkdownField(default=''),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='ExampleModel',
            name='text',
            field=markdownfield.models.MarkdownField(rendered_field='text_rendered'),
        ),
        migrations.RunPython(save_text_rendered),
    ]

License

This software is released under the MIT license.

Copyright (c) 2019-2026 Luke Rogers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_markdownfield-0.13.2.tar.gz (790.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_markdownfield-0.13.2-py3-none-any.whl (749.3 kB view details)

Uploaded Python 3

File details

Details for the file django_markdownfield-0.13.2.tar.gz.

File metadata

  • Download URL: django_markdownfield-0.13.2.tar.gz
  • Upload date:
  • Size: 790.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for django_markdownfield-0.13.2.tar.gz
Algorithm Hash digest
SHA256 aa3cc557b5bd691c144ccde18d8cdb409facf35b4b43d24e16a6a24189d9273f
MD5 bd2bffd102a01eb95d9fd537ed8cb6bd
BLAKE2b-256 3db9d92a67e768645f373fb98e5e0fc0407051017eb2df1c0062bbf3f352e365

See more details on using hashes here.

File details

Details for the file django_markdownfield-0.13.2-py3-none-any.whl.

File metadata

  • Download URL: django_markdownfield-0.13.2-py3-none-any.whl
  • Upload date:
  • Size: 749.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for django_markdownfield-0.13.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1a2700e2308889133004df4a854416d53a96a92f562bc4f86e3f2210868bcdb8
MD5 3c006c108d1e18a93294e1a959a41f8e
BLAKE2b-256 460795c3165903355be26ac06f3b101e302fe1552d0faa9dc525b0e2e1bcb88c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page