Coder Social home page Coder Social logo

django-markdownify's Introduction

Django Markdownify - A Django Markdown filter

PyPi Downloads License Documentation Status Version

Django Markdownify is a template filter to convert Markdown to HTML in Django. Markdown is converted to HTML and sanitized.

Read the full documentation on Read the docs or check out the package on pypi.

Warning

The old settings are removed in release 0.9.4! Please update to the new settings as soon as possible.

Usage

Load the tag inside your template:

{% load markdownify %}

Then you can change markdown to html as follows:

{{ 'text'|markdownify }}

or

{{ somevariable|markdownify }}

Example

{% load markdownify %}
{{'Some *test* [link](#)'|markdownify }}

Is transformed to:

<p>
  Some <em>test</em> <a href="#">link</a>
</p>

The filter is a wrapper around Markdown and Bleach and as such supports their settings. It is possible to define multiple settings for multiple usecases.

For example:

# settings.py

MARKDOWNIFY = {
  "default": {
     "WHITELIST_TAGS": ["a", "p", "h1", ]
  },

  "alternative": {
     "WHITELIST_TAGS": ["a", "p", ],
     "MARKDOWN_EXTENSIONS": ["markdown.extensions.fenced_code", ]
  }
}

And in your templates:

<!-- page1.html -->
{{ mytext|markdownify }} <!-- Uses your default settings -->

<!-- page2.html -->
{{ mytext|markdownify:"alternative" }} <!-- Uses your alternative settings -->

Documentation

Read the full documentation on Read the docs.

Credits

This filter is a slightly richer and packaged version of the snippet: using-markdown-django-17.

django-markdownify's People

Contributors

datagreed avatar davidbgk avatar dependabot[bot] avatar dplanella avatar erwin-academie-dev avatar erwinmatijsen avatar jspaans91 avatar raratiru avatar rob32 avatar rrmoelker avatar skwalexe 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

django-markdownify's Issues

Conflicting Python package names

I cannot use your package and the following package at the same time:

matthewwithanm / python-markdownify

and yours. Both has the conflicting package names. I use both packages in my django project. Somehow it works on my development machine but it breaks if I package it into Docker image.

File "/edscc/edscc/core/utils.py", line 16, in <module>
    from markdownify import markdownify as md
ImportError: cannot import name 'markdownify' from 'markdownify' (/usr/local/lib/python3.7/site-packages/markdownify/__init__.py)

Your package overwrites matthewwithanm's package when building a docker image.

Recommended fix is to rename your package folder to something else so it doesn't conflict with the above package.

Add tag for 0.9.3 on github

hey, I saw that version 0.9.3 was out on pipy and got updated on this repo on 886aea6 but there's no tag to see exactly which commit is the first of 0.9.3

Bleach is deprecated

See this issue in the Bleach repository. An underlying lib is no longer maintained, and Bleach will also be deprecated because of that.

From that issue:

As of now, Bleach is deprecated.

We will continue to support Bleach:

security updates
support for new Python versions
fixes for egregious bugs

So, main functionality will still work in the near future. But maybe we should consider removing Bleach as a dependency.

module 'bleach.sanitizer' has no attribute 'ALLOWED_STYLES'

Since Bleach version 5.0.0 the sanitation of CSS style tags is completely refactored and placed in a separate package. Therefore the attribute ‘ALLOWED_STYLES’ is completely removed and is not accepted anymore.

This causes the following error when using this package:

module 'bleach.sanitizer' has no attribute 'ALLOWED_STYLES'

Support for markdown extensions?

I found that multi-lined fenced code blocks doesn't working out of the box. How about adding support of markdown extension to load?

settings:

MARKDOWNIFY_MARKDOWN_EXTENSIONS = ['markdown.extensions.fenced_code']

module:

 html = markdown.markdown(text, extensions=MARKDOWNIFY_MARKDOWN_EXTENSIONS)

Bleaching messes with paragraphs

Steps to reproduce

Say I have a description variable with the following content:

A short paragraph.

Another paragraph.

In my template, I have {{description|markdownify}}.

Expected output

<p>A short paragraph.</p>
<p>Another paragraph.</p>

Actual output

A short paragraph.
Another paragraph.

This is definitely not what I expected. One of the main reasons for using Markdown in the first place is to avoid manually inserting paragraphs.

If I set MARKDOWNIFY_BLEACH = False in my settings, I get the correct output.

line breaks

First of all thank you for your package :) 👍 all the Markdown parsers for Django seems to be 8+ years old at least : 🌊
Quick question: how can I rended line breaks ?

At the moment I am using
{{ value|markdownify|linebreaksbr }}

but perhaps there is a better way?
Thanks!

Can I add a class to a table?

Heyho, is it possible to add a CSS class to a table or something?

I can configure as allowed attributes the following settings:

MARKDOWNIFY_WHITELIST_ATTRS = [
    'href',
    'src',
    'alt',
    'class',
]

In my case, I want to add table table-hover table-striped classes to a table, but I do not know how to do this. And I can only find it in the python code examples, but not from within the markdown itself. Is it possible to add classes?

Your documentation points to this page: https://bleach.readthedocs.io/en/latest/clean.html#allowed-attributes-attributes
But they are using the attrs on the html code itself, not on markdown representations.

Thanks for your help :)

Documention could suggest using `filter markdownify`.

As currently documented, django-markdownify won't work with template tags. But you can use {% filter markdownify %} instead of {% markdownify %}. In that case, Python-Markdown will process the text after the template substitution, and dynamic content will work, e.g.

<https://{{ domain }}/help/flyer.pdf>

Tests fail

when I installed this with pip install django-markdownify, none of the *.md files in the tests directory were downloaded so all tests fail with FileNotFoundError.

Paragraphs without whitespace break template layout

I've encountered an issue with very long strings with no whitespace that fall under different markdown elements (p, h1, etc.)

<div class="parent">
    {{ string|markdownify }}
</div>

The rendered element in the template breaks the parent element of a certain width. I've tested with a string that is structurally considered to be like a sentence and the string wraps in the event that it reaches the maximum length of the container and wraps to the next line.

Not sure if it has to do with the filter itself when it comes to strings with whitespace versus strings with characters with no whitespace.

Issues with providing alternative settings

I followed the setup in the documentation, however whenever I place {{ content|markdownify:"alternative" }} into my index.html folder I get the error markdownify requires 1 arguments, 2 provided. Markdownify works perfectly when it is not given alternative settings.

WHITELIST_TAGS don't work

I used WHITELIST_TAGS in setting.py but don't work.

markdownify.markdownify("sdf<ul><li><b>aaa</b></li></ul>", heading_style="ATX", whitelist_tags=["ul", "li"])

please help me :(

Specifying different settings in different views/files

Hey,

I'm finding the need to specify different settings on different endpoints, basically I want do have the allowed tags set for the whole app but not on one specific view, where no tags are allowed.

I don't think this is possible with the current code, so I'll make a copy of the filter where I can specify the settings

Do you think this would be worth being added as a new enhancement?

Maintaining

@RRMoelker Are you interested in maintaining this package? I (and @alexhayes) made some small additions and improvements which could benefit others as well.

I don't really want to push a fork to PyPi, so I would be glad to take over maintenance of your package.

Rendering of a table not possible

Hello,

I am looking for a Markdown library, which makes it possible to render tables from markdown. Your lib seems to be not capable of this feature, am I right in this point?

What I have tried so far:

  1. Installed markdownify from pypi
"django-markdownify": {
            "hashes": [
                "sha256:28ee91769c97a7374716ce0fd1dcd3094fc3405af8b876db88e9787401adb40b",
                "sha256:42de7e691c0a9239bda8540de57a254d70c938bdb09f514dcafa9c197a06e6fa"
            ],
            "index": "pypi",
            "version": "==0.8.2"
        }
  1. Using Django 2.2.17
  2. Enabling markdownify in a template of the static-page app:
# ...
{% load markdownify %}

{% block heading %}
  <h1>{{ page.title }}</h1>
{% endblock %}

{% block content %}
  <p>
    {{ page.content|markdownify }}
  </p>
{% endblock %}
  1. Input value for the table:
| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |


**verify that markdown is rendered**
  1. Result:
    image

Do you have any ideas on this issue? Or is simply not possible to render tables with your library?

Thanks :-)

Can't decode images

![By NASA (NASA) Public domain, via Wikimedia Commons](https://upload.wikimedia.org/wikipedia/commons/8/8c/Mosaic_of_the_Arctic.jpg "Earth")
Does not get converted properly to
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8c/Mosaic_of_the_Arctic.jpg" title="Earth">

AttributeError: module 'bleach' has no attribute 'css_sanitizer'. Did you mean: 'sanitizer'?

whitelist_tags = markdownify_settings.get('WHITELIST_TAGS', bleach.sanitizer.ALLOWED_TAGS)
whitelist_attrs = markdownify_settings.get('WHITELIST_ATTRS', bleach.sanitizer.ALLOWED_ATTRIBUTES)
whitelist_styles = markdownify_settings.get('WHITELIST_STYLES', bleach.css_sanitizer.ALLOWED_CSS_PROPERTIES)
whitelist_protocols = markdownify_settings.get('WHITELIST_PROTOCOLS', bleach.sanitizer.ALLOWED_PROTOCOLS)

Line 25 is the source of the error.

setup.py failes trying to read "README.rst"

Hi,
maybe i am overlooking something simple, but i tried to build this package using

python setup.py build

which resulted in it failing with

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
FileNotFoundError: [Errno 2] No such file or directory: 'README.rst

And indeed the file is missing. Could you maybe explain why you changed that line in bb6b7b6 ? Sorry in advance if this is a stupid or obvious thing..

add {% markdownify %} {% endmarkdownify %} templatetags

in many situations |markdownify is usable. But when it comes to more complex situations, the filter is not enough.
If I want to call something else instead of rendering a variable, you can't use it:

This works:
{{ my_var | markdownify }}

This doesn't:
{% custom_templatetag request.user | markdownify %}

Sure, this isn't correct template syntax.

What would work (alongside {% blocktranslate %}):

{% markdownify %}
  {% custom_templatetag request.user %}
{% endmarkdownify %}

It would be relaively easy to implement that, you could reuse the filter internally.

ID is not parsing in attributes

Example:

Mardown table:

## Table of Contents
- [Introduction](#introduction)
  - [Subtopic 1](#subtopic-1)
  - [Subtopic 2](#subtopic-2)
- [Main Content](#main-content)
  - [Chapter 1](#chapter-1)
    - [Section 1.1](#section-11)
    - [Section 1.2](#section-12)
  - [Chapter 2](#chapter-2)
- [Conclusion](#conclusion)

The above should be pointing to the corresponding heading:

# Introduction
## Subtopic 1
## Subtopic 2
# Main Content
## Chapter 1
### Section 1.1
### Section 1.2
## Chapter 2
# Conclusion

Output should be:

<h2>Table of Contents</h2>
<ul>
  <li><a href="#introduction">Introduction</a>
    <ul>
      <li><a href="#subtopic-1">Subtopic 1</a></li>
      <li><a href="#subtopic-2">Subtopic 2</a></li>
    </ul>
  </li>
  <li><a href="#main-content">Main Content</a>
    <ul>
      <li><a href="#chapter-1">Chapter 1</a>
        <ul>
          <li><a href="#section-11">Section 1.1</a></li>
          <li><a href="#section-12">Section 1.2</a></li>
        </ul>
      </li>
      <li><a href="#chapter-2">Chapter 2</a></li>
    </ul>
  </li>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>

<h1 id="introduction">Introduction</h1>
<h2 id="subtopic-1">Subtopic 1</h2>
<h2 id="subtopic-2">Subtopic 2</h2>
<h1 id="main-content">Main Content</h1>
<h2 id="chapter-1">Chapter 1</h2>
<h3 id="section-11">Section 1.1</h3>
<h3 id="section-12">Section 1.2</h3>
<h2 id="chapter-2">Chapter 2</h2>
<h1 id="conclusion">Conclusion</h1>

But the id is not parsed in the django template.
Even added the ID in whitelisting


        "WHITELIST_ATTRS": [
            'href',
            'src',
            'alt',
            'class',
            'id'
        ],

MARKDOWNIFY_WHITELIST_ATTRS style color

Hello,
In your README you do not precise how to set the attributes for the style attributes.
As written in the bleach doc :

>>> attrs = {
...     '*': ['style']
... }
>>> styles = ['color', 'font-weight']

Is it possible with your markdownify or should I modify it ?
Thanks !

[edit] I just created a pull request [/edit]

Emoji support

It is common that editors that support markdown also support emojis, using codes like :+1: which translates to corresponding emoji 👍

Extending Support for Syntax Highlighting via Codehilite

Extending Issue #6

Background

Looks like fenced_code extension now works but looks like the Syntax highlighting is still not working.

I've done the following in my Settings.py file for the project

https://github.com/ss4328/django_dev_blog

MARKDOWNIFY = {
    "default": {
        "MARKDOWN_EXTENSIONS": [
            'markdown.extensions.fenced_code',
            'markdown.extensions.extra'
        ],
        "WHITELIST_STYLES": [
            'color',
            'font-weight',
        ]
    }
}

MARKDOWNIFY_WHITELIST_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'em',
'i',
'li',
'ol',
'p',
'strong',
'ul',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'img',
'code'
]

MARKDOWNIFY_WHITELIST_ATTRS = [
'href',
'src',
'alt',
]

MARKDOWNIFY_WHITELIST_STYLES = [
'color',
'font-weight',
]

MARKDOWNIFY_WHITELIST_PROTOCOLS = [
'http',
'https',
]

Problem

Either we're not supporting syntax-highlighting out of the box, or looks like I'm missing something rudimentary. The code block is being recognized (as evident by the pink color), but looks like syntax highlighting is not working (as evident by missing new lines, and missing background styling)

Screen Shot 2021-03-23 at 9 09 22 PM

Screen Shot 2021-03-23 at 9 09 32 PM

I've tried to follow

I also Installed pygments and generated+loaded CSS but syntax highlighting is missing.

Naming conflict with python-markdownify package

I've noticed that the name of this project, "django-markdownify", clashes with another popular Python package, "python-markdownify" maintained by Matthewwithanm. If both "django-markdownify" and "python-markdownify" packages are installed in the same virtual environment, it can cause conflicts as they have the same package name. When importing the "markdownify" package in a Python script, it will be ambiguous which package is actually being referred to.

Are Headings Not Supported?

I'd like to easily utilize headings in Django-Markdownify. I can work on this if necessary, but this seems like quite a drawback.

E.g., if I had:

### FooBarBob

When I run 'markdownify' I'd expect this to get translated to:

<h3>FooBarBob</h3>

Please see https://www.markdownguide.org/basic-syntax/ with any questions or let me know.

Cheers,
Yemar

Headers (#) do not get interpreted as h1,h2,etc.

I have some markdown I am rendering to HTML such as my header below (# My Header)

My Header

Problematically, this does not get interpreted as a header, so it is not emphasized, but there are also newline issues. That is, there is no line break after the header.

Can you please on advise on whether I should expect these headers to be rendered as HTML headers?

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.