Released:
At first I successfully install django markdown pip install django-markdown than I add django-markdown in my setting.py file INSTALLEDAPPS = 'django.contrib.admin', 'django.contrib.auth', '. Django-markdown2 depends on python-markdown2, which can be found at http://code.google.com/p/python-markdown2. You can now write your own Python programs that take advantage of the Markdown syntax in different contexts, such as web applications using a web framework like Flask or Django. For a tutorial on how to build an app with Python-Markdown and Flask, read How To Use Python-Markdown with Flask and SQLite.
a Django app that provides template tags for using Markdown (using the python-markdown2 processor)
Project description
[Markdown](http://daringfireball.net/projects/markdown/) using the
[python-markdown2](https://github.com/trentm/python-markdown2) library.
# What's with the 'deux' in the name?
The obvious name for this project is `django-markdown2`. However, there
[already is one!](http://github.com/svetlyak40wt/django-markdown2) and name
confusion doesn't help anybody. Plus, I took French immersion in school for 12
years: might as well put it to use.
# So why another project then?
Because I wanted to do something slightly different. Django-markdown2's
`markdown` filter takes
['extras'](https://github.com/trentm/python-markdown2/wiki/Extras) as arguments
-- with the one exception that 'safe' is transformed to python-markdown2's
`safe_mode` argument. This is handy for quick usage. My use case is more
commonly: lots of `markdown` filter and block usage in my Django templates with
the same set of python-markdown2 options.
# Installation
Choose the *one* of the following that works best for you:
- Install the latest release from PyPI:
pip install django-markdown-deux
or, if you use [ActivePython](http://www.activestate.com/activepython):
pypm install django-markdown-deux
These should install the dependent `python-markdown2` package.
- Get a git clone of the source tree:
git clone git://github.com/trentm/django-markdown-deux.git
You might want a particular tag:
cd django-markdown-deux
git tag -l # list available tags
git checkout $tagname
Then you'll need the 'lib' subdir on your PYTHONPATH:
python setup.py install # or 'export PYTHONPATH=`pwd`/lib:$PYTHONPATH'
You'll also need the [python-markdown2
library](https://github.com/trentm/python-markdown2):
git clone git@github.com:trentm/python-markdown2.git
cd python-markdown2
python setup.py install # or 'export PYTHONPATH=`pwd`/python-markdown2/lib'
# Django project setup
1. Add `markdown_deux` to `INSTALLED_APPS` in your project's 'settings.py'.
2. Optionally set some of the `MARKDOWN_DEUX_*` settings. See the 'Settings'
section below.
# Usage
The `markdown_deux` facilities typically take an optional 'style' argument. This
is a name for a set of options to the `python-markdown2` processor. There is
a 'default' style that is used if no argument is given. See the
`MARKDOWN_DEUX_STYLES` setting below for more.
## `markdown` template filter
{% load markdown_deux_tags %}
...
{{ myvar|markdown:'STYLE' }} {# convert `myvar` to HTML using the 'STYLE' style #}
{{ myvar|markdown }} {# same as `{{ myvar|markdown:'default'}}` #}
## `markdown` template block tag
{% load markdown_deux_tags %}
...
{% markdown STYLE %} {# can omit 'STYLE' to use the 'default' style #}
This is some **cool**
[Markdown](http://daringfireball.net/projects/markdown/)
text here.
{% endmarkdown %}
## `markdown_allowed` template tag
In a template:
{% markdown_allowed %}
will emit a short HTML blurb that says Markdown syntax is allowed. This can be
handy for placing under form elements that accept markdown syntax. You can also
use it as the `help_text` for a form field something like:
# myapp/forms.py
from markdown_deux.templatetags.markdown_deux_tags import markdown_allowed
class MyForm(forms.Form):
#...
description = forms.CharField(
label='Description (required)',
widget=forms.Textarea(attrs={'rows': 5}),
help_text=_secondary_span('A brief description of your thing.<br/> '
+ markdown_allowed()),
required=True)
## `markdown_cheatsheet` tag
{% markdown_cheatsheet %}
This outputs HTML giving a narrow (appropriate for, e.g., a sidebar) listing of
some of the more common Markdown features.
## `markdown_deux.markdown(TEXT, STYLE)` in your Python code
The `markdown` filter and block tags above ultimately use this
`markdown_deux.markdown(...)` function. You might find it useful to do Markdown
processing in your Python code (e.g. in a view, in a model `.save()` method).
# Settings
All settings for this app are optional.
## `MARKDOWN_DEUX_STYLES` setting
A mapping of style name to a dict of keyword arguments for python-markdown2's
`markdown2.markdown(text, **kwargs)`. For example the default setting is
effectively:
MARKDOWN_DEUX_STYLES = {
'default': {
'extras': {
'code-friendly': None,
},
'safe_mode': 'escape',
},
}
I.e. only the 'default' style is defined and it just uses the [code-friendly
extra](https://github.com/trentm/python-markdown2/wiki/code-friendly) and escapes
raw HTML in the given Markdown (for safety).
Here is how you might add styles of your own, and preserve the default style:
# settings.py
from markdown_deux.conf.settings import MARKDOWN_DEUX_DEFAULT_STYLE
MARKDOWN_DEUX_STYLES = {
'default': MARKDOWN_DEUX_DEFAULT_STYLE,
'trusted': {
'extras': {
'code-friendly': None,
},
# Allow raw HTML (WARNING: don't use this for user-generated
# Markdown for your site!).
'safe_mode': False,
}
# Here is what http://code.activestate.com/recipes/ currently uses.
'recipe': {
'extras': {
'code-friendly': None,
},
'safe_mode': 'escape',
'link_patterns': [
# Transform 'Recipe 123' in a link.
(re.compile(r'recipes+#?(d+)b', re.I),
r'http://code.activestate.com/recipes/1/'),
],
'extras': {
'code-friendly': None,
'pyshell': None,
'demote-headers': 3,
'link-patterns': None,
# `class` attribute put on `pre` tags to enable using
# <http://code.google.com/p/google-code-prettify/> for syntax
# highlighting.
'html-classes': {'pre': 'prettyprint'},
'cuddled-lists': None,
'footnotes': None,
'header-ids': None,
},
'safe_mode': 'escape',
}
}
## `MARKDOWN_DEUX_HELP_URL` setting
A URL for to which to link for full markdown syntax default. This link is
only in the output of the `markdown_allowed` and `markdown_cheatsheet`
template tags.
The default is <http://daringfireball.net/projects/markdown/syntax>, the
canonical Markdown syntax reference. However, if your site uses Markdown with
specific tweaks, you may prefer to have your own override. For example,
[ActiveState Code](http://code.activestate.com) uses:
MARKDOWN_DEUX_HELP_URL = '/help/markdown/'
To link to [its own Markdown syntax notes
URL](http://code.activestate.com/help/markdown/).
Release historyRelease notifications | RSS feed
1.0.5
1.0.4
1.0.3
1.0.2
Python Markdown2
1.0.1
1.0.0
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Filename, size | File type | Python version | Upload date | Hashes |
---|---|---|---|---|
Filename, size django-markdown-deux-1.0.5.zip (16.7 kB) | File type Source | Python version None | Upload date | Hashes |
Hashes for django-markdown-deux-1.0.5.zip
Algorithm | Hash digest |
---|---|
SHA256 | 5b4a3cd9454af5b4cec0e19151b41d98d09400ddae0688afb81dbf62a4edafff |
MD5 | 6e3016740f3164020ff93882bc7a6cf0 |
BLAKE2-256 | 80a5d61ee6fc26cbb0d737986ed23e13309c88f2ae7f1fcdf2460a525323a3ed |
Markdown editors are amazing when you want to write professional blogs, post or article but you don't want to get your hands messy with HTML formatting. You can easily integrate markdown editor in your Django project using django-mdeditor package and markdown package.
Want this awesome markdown editor in your Django project ? :D
Follow our simple step-by-step instructions to include a markdown editor into your Django project.
Environment
- Python Version: 3.5 and above
- Django: 2.x, 3.x
Step 1 - Install Django, django-mdeditor and markdown
Let's first create a virtualenv:
virtualenv -p python3.6 env
Next, let's activate the virtual environment:
source env/bin/activate
Install Django version 3.0, djang-mdeditor and markdown package:
pip install django3.0pip install django-mdeditorpip install markdown
Step 2 - Create Django project
Create a project named 'myproject':
django-admin startproject myproject
Switch to the project directory 'myproject':
cd myproject/
Create an app named 'myapp':
django-admin startapp myapp
Add 'myapp' in the INSTALLED_APPS section in project's settings.py.
myproject/settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', # <-- Add this 'mdeditor', # <-- Add this]
Step 3 - Create a Post table in Sqlite 3 database
Let's start with creating a model name Post in myapp having 2 attribues: title and content, where content will be body of a post (markdown editor field) and title will be post heading.
Create a model named Post in models.py of myapp:
myapp/models.py
from django.db import modelsfrom mdeditor.fields import MDTextField class Post(models.Model): title = models.CharField(max_length=120) content = MDTextField()
Next, let's register the model in admins.py so that it is visible in Django admin portal:
myapp/admin.py
from django.contrib import adminfrom .models import Postadmin.site.register(Post)
Add the MDEDITOR_CONFIGS in myproject's settings.py that controls mdeditor settings:
myproject/settings.py
MDEDITOR_CONFIGS = {'default':{ 'width': '100% ', # Custom edit box width 'heigth': 500, # Custom edit box height 'toolbar': ['undo', 'redo', '|', 'bold', 'del', 'italic', 'quote', 'ucwords', 'uppercase', 'lowercase', '|', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', '|', 'list-ul', 'list-ol', 'hr', '|', 'link', 'reference-link', 'image', 'code', 'preformatted-text', 'code-block', 'table', 'datetime' 'emoji', 'html-entities', 'pagebreak', 'goto-line', '|', 'help', 'info', '||', 'preview', 'watch', 'fullscreen'], # custom edit box toolbar 'upload_image_formats': ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp'], # image upload format type 'image_folder': 'editor', # image save the folder name 'theme': 'default', # edit box theme, dark / default 'preview_theme': 'default', # Preview area theme, dark / default 'editor_theme': 'default', # edit area theme, pastel-on-dark / default 'toolbar_autofixed': True, # Whether the toolbar capitals 'search_replace': True, # Whether to open the search for replacement 'emoji': True, # whether to open the expression function 'tex': True, # whether to open the tex chart function 'flow_chart': True, # whether to open the flow chart function 'sequence': True, # Whether to open the sequence diagram function 'watch': True, # Live preview 'lineWrapping': False, # lineWrapping 'lineNumbers': False, # lineNumbers 'language': 'en' # zh / en / es }}
These settings control the language, image folder location, image upload format etc. of the markdown editor.
Note that if you want to upload any image using the markdown editor, you have to do settings related to uploading images in Django. Follow article How to create image upload button in Django? for this if needed.
Migrate the model to Sqlite 3 database by executing below command:
python manage.py makemigrationspython manage.py migrate
Create an admin user in log into Django admin portal:
python manage.py createsuperuser
Enter Username, Email address and Password of your choice.Log into the Django admin panel using admin credentials and confirm if you can create a new entry in Post table as shown:
http://127.0.0.1:8000/admin/myapp/post/add/
Step 4 - HTML web page to create post
Django admin panel cannot be used to create post always. You will need an HTML web page that would provide a front-end for this. Follow along to accomplish this.
Create a url for create_post.html in urls.py:
myproject/urls.py
from django.contrib import adminfrom django.urls import pathfrom myapp import views # <-- Add thisurlpatterns = [ path('admin/', admin.site.urls), path('create_post/', views.create_post, name='create_post'), # <-- Add this]
Create a form for Post model under myapp folder:
myapp/forms.py
from django import formsfrom .models import Postfrom mdeditor.widgets import MDEditorWidgetclass PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content') widgets = { 'title': forms.TextInput(), 'content': MDEditorWidget(), }
Create a view named create_post to render create_post.html page:
myapp/views.py
from django.shortcuts import render, redirectfrom .models import Postfrom .forms import PostFormdef create_post(request): form = PostForm(request.POST or None, request.FILES or None) if request.method 'POST': if form.is_valid(): form.save() return redirect('create_post') else: print(form.errors) context = {'form':form} return render(request,'create_post.html',context)
The view creates empty form if request is GET. If the request is POST, it checks the form data and saves it if the form is valid in Post model.
Next, let's create HTML web page named create_post.html. Create templates folder in myapp:
mkdir myapp/templates
Create create_post.html template in myapp:
myapp/templates/create_post.html
<html><head><link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'></head><body> <div> <h2>Create Post</h2> {{ form.media }} <form action=' method='POST' enctype='multipart/form-data' novalidate accept-charset='utf-8' > {% csrf_token %} {{ form.as_p }} <button type='submit'>Submit</button> </form> </div></body></html>
Run Django server and confirm below web page:
python manage.py runserver
127.0.0.1:8000/create_post
Step 5 - Display all post created
Now that you know how to use mdeditor to create a post, next step is to display list of all post created so far.
Create url entry as shown:
myproject/urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('create_post/', views.create_post, name='create_post'), path('display_post/', views.display_post, name='display_post'), # <-- Add this]
Create display_post in views.py:
myapp/views.py
def display_post(request): all_post = Post.objects.all() context = { 'posts':all_post, } return render(request, 'display_post.html', context)
Let's create HTML template display_post.html as shown:
myapp/templates/display_post.html
<html><head> <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'></head><body> <div> <h2>Post Created</h2> <ul> {% for post in posts %} <li>{{ post.title }}</li> {% endfor %} </ul> <a href='{% url 'create_post' %}'>Create Post</a> </div></body></html>
Run Django server to confirm you can view the display_post.html page:
python manage.py runserver
127.0.0.1:8000/display_post:
Step 6 - Display markdown content on web page
The last step would be to display markdown content of post on web page.
Markdown content can be converted into HTML code using mark_safe() function. Modify Post model and include a function named get_message_as_markdown() as shown:
myapp/models.py
from django.db import modelsfrom django.utils.html import mark_safe # Add thisfrom markdown import markdown # Add thisfrom mdeditor.fields import MDTextField class Post(models.Model): title = models.CharField(max_length=120) content = MDTextField() def get_message_as_markdown(self): # Add this return mark_safe(markdown(self.content, safe_mode='escape')) # Add this
To display all post, create a URL for post that will take post's id as argument:
myproject/urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('create_post/', views.create_post, name='create_post'), path('display_post/', views.display_post, name='display_post'), path('post/<id>', views.post, name='post'), # <-- Add this]
Let's create view named post to display the post as mentioned in the urls.py:
myapp/views.py
from django.shortcuts import render, get_object_or_404, reverse,redirect # <-- Add this def post(requests, id): <-- Create this function post_display = get_object_or_404(Post, id=id) context = { 'post': post_display, } return render(requests, 'post.html', context)
Finally, create HTML template post.html to display the post. Notice the post is displayed using the fucntion get_message_as_markdown:
myapp/templates/post.html
<html><head> <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'></head><body> <div> {{ post.get_message_as_markdown }} </div> </body></html>
Also, let's modify HTML template display_post.html to contain a tag for each post title:
myapp/templates/display_post.html
<html><head> <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'></head><body> <div> <h2>Post Created</h2> <ul> {% for post in posts %} <li><a href='{% url 'post' post.id %}'>{{ post.title }}</a></li> <!-- Add this--> {% endfor %} </ul> <a href='{% url 'create_post' %}'>Create Post</a> </div></body></html>
Run Django server and confirm you can see the links for each post:
python manage.py runserver
Confirm that display_post is showing links for all post:
http://127.0.0.1:8000/display_post/
Confirm that on clicking one of the Post I, you can see web page as shown:
127.0.0.1:8000/post/1/:
Conclusion
Django Markdown Editor
In this tutorial, using django-mdeditor and markdown module, you created a sample project that include a markdown editor that you can use for blog writing. Next you might be interested in How to use Rich Text Editor like tinymce in Django?
Have any question or feedback on this tutorial? Drop us a comment and we'd love to answer your queries!