Coder Social home page Coder Social logo

django-markdown-deux's Introduction

A small Django app that provides template tags for using Markdown using the 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! 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" 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:

      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:

      git clone [email protected]: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 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"recipe\s+#?(\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 uses:

MARKDOWN_DEUX_HELP_URL = "/help/markdown/"

To link to its own Markdown syntax notes URL.

django-markdown-deux's People

Contributors

graingert avatar martinleblanc avatar melkon98 avatar mlissner avatar mrooney avatar plumdog avatar trentm avatar xrmx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-markdown-deux's Issues

Support underscore method

Would it be possible to add support for underscores and to treat them the same as the asterisks.

So *Markdown* would provide the same as _Markdown_

comments

I am templates that are entirely markdown. I don't mind adding the template tags but I don't want them displayed in 3rd party markdown renderers, so I would like some way to comment them out like
[//]: # ({% load markdown_deux_tags %})
so that Github won't display it but they will still function as template tags

Compatibility with markdown2 v2.3.2?

I pip-installed django-markdown-deux today and I got:

markdown2==2.3.2
django-markdown-deux==1.0.5

Processing an .md file was broken however. Only the last ~=250 chars of the .md file seemed to get output as HTML. (Python 2.7.11 on Mac)

Changing back to markdown2==2.3.1 and the site works again.

Markdown is URL encoding my images links in Templates

Everything is working fine after installation, I am also using https://github.com/timmyomahony/django-pagedown for Admin.

When I insert the images with URL links and do not use {{ article.description }} instead of {{ article.description|markdown }} I can see the URL just fine like this:

"http://www.example.com/image.jpg" in templates.

In the Admin:

![image title][1]
[1]: http://www.example.com/image.jpg

But as soon as I add template tag "markdown" - {{ article.description|markdown }}

HTML output is <img src="http%3A%2F%2Fwww.example.com%2Fimage.jpg"> and the image cannot be loaded. I have tried it on my 2 projects if I am wrong in some way but the same result.

Fenced code blocks do not receive pre tag

Suppose I have a database entry where I have the following "fenced code block"

(triple back tick)
some fenced code block
another line
(triple back tick)

I also have the following model method in django models.py

def get_markdown(self):
        return mark_safe(markdown(self.body))
        where body = models.TextField()

Then the result being returned by the method is the following html code...

<p><code>
some fenced code block
another line
</code></p>

The <pre> tag is missing and it also displays inline rather than receiving the line break.

Invalid filter: 'markdown' django-markdown-deux

Before I explain my issue, let me tell you some basics of my system:
windows 10
python 3.6
django 1.9

I followed the documention of 'django-markdown-deux', from it, I learned it has four steps to be implemented.

Firstly: pip3 install django-markdown-deux

Secondly: add 'markdown_deux' into your INSTALLED_APP

Thirdly: add {% load markdown_deux_tags %} into your header.html

Finally: add {{ post.body|markdown }}, as I want to transfer post.body to markdown

{% extends "personal/header.html" %}
{% block content %}

<h3><a href="/blog/{{post.id}}">{{ post.title }}</a></h3>
<h6> on {{ post.date }}</h6>

<div class = "container">
	{{ post.body|markdown }}
</div>
<br><br>
{% endblock %}

after doing this, I have "Error during template rendering"

In template F:\django\mysite_1\blog\templates\blog\post.html, error at line 8

Invalid filter: 'markdown'

sections inside markdown block

Hi,

sections inside the markdown block apparently interrupt the markdown:

{% markdown %} ## Markdown works
## No Markdown rendering :(
{% endmarkdown %}

Is it meant like that? Can I somehow use sections inside a markdown block?

Django 2.1 support

I tried django 2.1 today as I saw that view permision's added, but found that error occurs when I tried to add a post.
TypeError: render() got an unexpected keyword argument 'renderer' .
Further detail as follows
image

Feature request: include markdown in templates

Would it be possible to create an includemd template tag similar to the django include tag which is used to include fragments? For example, in a regular django template, I'd like to pull in the text content from somefile.md as follows:

<div class="row">
{% includemd "somefile.md" %}
</div>

If you think this would be possible, I'll look into it and open a pull request.

Discussion: Has anyone found a viable alternative or maintained fork?

Hi Everyone,

What are people using as alternatives to this great (but now unmaintained) package? Googling around I can't find anyone else filling this niche of markdown within django templates. Not as nicely as this package did anyway.

PS: Trentm if you happen to see this. Thank you for the package. I completely understanding wanting to leave it be. But thank you again for the time you put into it.

Django 4.0 support

In case somebody else will be looking for this, Django 4.0 is not supported at the moment:

django.template.library.InvalidTemplateLibrary: 
Invalid template library specified. ImportError raised when trying to load
'markdown_deux.templatetags.markdown_deux_tags': 
cannot import name 'force_unicode' from 'django.utils.encoding' 
(/Users/mmalysh/Dev/my-website/venv/web-3.10/lib/python3.10/site-packages/django/utils/encoding.py)
make: *** [sync] Error 1

Django 3.2 still works for us.

Table support + style help

Does this support table syntax,

column 1 column 2
data 1 data 2

etc.

Also, any guidance on how to set STYLE to make some restful api docs look good ?

Thanks Dave

<br> elements showing up in lists

When the break-on-newline setting is set to True, line breaks are inserted into lists.

settings.py

MARKDOWN_DEUX_STYLES = {
    "default": {
        "extras": {
            "break-on-newline": True,
        }
    }
}

For example, when this setting is enabled a markdown list with nested list items renders like this:
image

To me, it would make sense if the line breaks were not rendered within list element so that the appearence would look more like this:
image

Would you consider this a bug?

Styles not working

I'm trying to use styles with the markdown templatetag. I've setup settings.MARKDOWN_DEUX_STYLES to match the 3 styles in the README -- but regardless of which I call (trusted or recipe), the "default" style always gets used.

In [14]: from markdown_deux.conf import settings

In [15]: settings.MARKDOWN_DEUX_STYLES
Out[15]: {'default': {'extras': {'code-friendly': None}, 'safe_mode': 'escape'}}

In [16]: settings.settings.MARKDOWN_DEUX_STYLES                                                                                                                         
Out[16]: 
{'default': {'extras': {'code-friendly': None}, 'safe_mode': 'escape'},
 'recipe': {'extras': {'code-friendly': None,
   'cuddled-lists': None,
   'demote-headers': 3,
   'footnotes': None,
   'header-ids': None,
   'html-classes': {'pre': 'prettyprint'},
   'link-patterns': None,
   'pyshell': None},
  'link_patterns': [(re.compile(r'recipe\s+#?(\d+)\b', re.IGNORECASE),
    'http://code.activestate.com/recipes/\\1/')],
  'safe_mode': 'escape'},
 'trusted': {'extras': {'code-friendly': None}, 'safe_mode': False}}

# notice how it returns "default" even though "trusted" is being requested
In [18]: markdown_deux.get_style('trusted')
Out[18]: {'extras': {'code-friendly': None}, 'safe_mode': 'escape'}

It looks like the get_style function is only looking at the default settings, and not the updated settings.

Setting Extras to None is Confusing

So...I want to allow people to do cuddled lists. So, I'm like, cool, I'll turn on the cuddled-lists extra. And to do that, I set the value to...None.

Could we make it so that the value is instead set to True? I'm finding this super confusing. Even the code-friendly extra...is set to None? What does None mean in this context? I'm not sure I get it.

Python3 support

Hey,

i'm currently using django-markdown-deux with Python 3.5 without any problems. Should there be an Programming Language :: Python :: 3 indicator in the setup.py so that people won't assume that this package is not PY3K ready?

Mark downed text surrounded with <p> tags all over

Currently I'am Working On A Chat app and decided to have some md look in it.
but i have an issue with this the markdown is working properly but the text is surrounded by

tags!

here is a giant screenshot of it.

djangomderror

Bypass Django-markdown-deux XSS

Hi,

problem code :

     import re
     import markdown2
     text = re.sub(r'\[(.*?)\]\(javascript:(.*?)\)', r'\[\1\]\(javascript:\2\)', text)

Bypass:

1)[XSS](jav&#x0D;ascript:alert('XSS');)

2)[XXX](                                      javascript:alert('123');)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.