Giter VIP home page Giter VIP logo

wagtail-markdown's Introduction

wagtail-markdown: Markdown fields and blocks for Wagtail

Build status PyPI Ruff pre-commit.ci status

Tired of annoying rich text editors getting in the way of your content input? Wish Wagtail worked more like a wiki? Well, now it can.

wagtail-markdown provides Markdown field support for Wagtail. Specifically, it provides:

  • A wagtailmarkdown.blocks.MarkdownBlock for use in StreamFields.
  • A wagtailmarkdown.fields.MarkdownField for use in Page models.
  • A markdown template tag.

The markdown rendered is based on python-markdown, but with several extensions to make it actually useful in Wagtail:

These are implemented using the python-markdown extension interface.

Installation

Available on PyPI - https://pypi.org/project/wagtail-markdown/.

Install using pip (pip install wagtail-markdown), poetry (poetry add wagtail-markdown) or your package manager of choice.

After installing the package, add wagtailmarkdown to the list of installed apps in your settings file:

# settings.py

INSTALLED_APPS = [
    # ...
    "wagtailmarkdown",
]

Configuration

All wagtail-markdown settings are defined in a single WAGTAILMARKDOWN dictionary in your settings file:

# settings.py

WAGTAILMARKDOWN = {
    "autodownload_fontawesome": False,
    "allowed_tags": [],  # optional. a list of HTML tags. e.g. ['div', 'p', 'a']
    "allowed_styles": [],  # optional. a list of styles
    "allowed_attributes": {},  # optional. a dict with HTML tag as key and a list of attributes as value
    "allowed_settings_mode": "extend",  # optional. Possible values: "extend" or "override". Defaults to "extend".
    "extensions": [],  # optional. a list of python-markdown supported extensions
    "extension_configs": {},  # optional. a dictionary with the extension name as key, and its configuration as value
    "extensions_settings_mode": "extend",  # optional. Possible values: "extend" or "override". Defaults to "extend".
    "tab_length": 4,  # optional. Sets the length of tabs used by python-markdown to render the output. This is the number of spaces used to replace with a tab character. Defaults to 4.
}

Note: allowed_tags, allowed_styles, allowed_attributes, extensions and extension_configs are added to the default wagtail-markdown settings.

Custom FontAwesome Configuration - autodownload_fontawesome

The EasyMDE editor is compatible with FontAwesome 5. By default, EasyMDE will get version 4.7.0 from a CDN. To specify your own version, set

# settings.py

WAGTAILMARKDOWN = {
    # ...
    "autodownload_fontawesome": False,
}

Get the desired FontAwesome version. For the latest version you can use:

curl -H "Content-Type: application/json" \
-d '{ "query": "query { release(version: \"latest\") { version } }" }' \
https://api.fontawesome.com

then add the following to a wagtail_hooks module in a registered app in your application:

# Content of app_name/wagtail_hooks.py
from wagtail import hooks
from django.conf import settings
from django.utils.html import format_html


@hooks.register("insert_global_admin_css")
def import_fontawesome_stylesheet():
    elem = '<link rel="stylesheet" href="{}path/to/font-awesome.min.css">'.format(
        settings.STATIC_URL
    )
    return format_html(elem)

Note that due to the way EasyMDE defines the toolbar icons it is not compatible with Wagtail FontAwesome

Using with django-compressor

You may have your own SCSS sources that you want to precompile on the fly. We can invoke django-compressor to fetch our Font Awesome SCSS sources like this:

# Content of app_name/wagtail_hooks.py
from compressor.css import CssCompressor
from wagtail import hooks
from django.conf import settings
from django.utils.html import format_html


@hooks.register("insert_global_admin_css")
def import_fontawesome_stylesheet():
    elem = '<link rel="stylesheet" type="text/x-scss" href="{}scss/fontawesome.scss">'.format(
        settings.STATIC_URL
    )
    compressor = CssCompressor("css", content=elem)
    output = ""
    for s in compressor.hunks():
        output += s
    return format_html(output)

Markdown extensions - extensions/extension_configs

You can configure wagtail-markdown to use additional Markdown extensions using the extensions setting.

For example, to enable the Table of Contents and Sane Lists extensions:

WAGTAILMARKDOWN = {
    # ...
    "extensions": ["toc", "sane_lists"]
}

Extensions can be configured too:

WAGTAILMARKDOWN = {
    # ...
    "extension_configs": {"pymdownx.arithmatex": {"generic": True}}
}

Allowed HTML - allowed_styles / allowed_attributes / allowed_tags

wagtail-markdown uses bleach to sanitise the input. To extend the default bleach configurations, you can add your own allowed tags, styles or attributes:

WAGTAILMARKDOWN = {
    # ...
    "allowed_tags": ["i"],
    "allowed_styles": ["some_style"],
    "allowed_attributes": {"i": ["aria-hidden"]},
}

Syntax highlighting

Syntax highlighting using codehilite is an optional feature, which works by adding CSS classes to the generated HTML. To use these classes, you will need to install Pygments (pip install Pygments), and to generate an appropriate stylesheet. You can generate one as per the Pygments documentation, with:

from pygments.formatters import HtmlFormatter

print(HtmlFormatter().get_style_defs(".codehilite"))

Save the output to a file and reference it somewhere that will be picked up on pages rendering the relevant output, e.g. your base template:

<link rel="stylesheet" type="text/css" href="{% static 'path/to/pygments.css' %}">

EasyMDE configuration

You can customise the EasyMDE options. To do this, create a JavaScript file in your app (for example my_app_name/static/js/easymde_custom.js) and add the following:

window.wagtailMarkdown = window.wagtailMarkdown || {};
window.wagtailMarkdown.options = window.wagtailMarkdown.options || {};
window.wagtailMarkdown.options.spellChecker = false;

This overrides a specific option and leaves any other ones untouched. If you want to override all options, you can do:

window.wagtailMarkdown = window.wagtailMarkdown || {};
window.wagtailMarkdown.options = {
    spellChecker: false,
}

To make sure that your JavaScript is executed, create a hook in my_app_name/wagtail_hooks.py:

from django.templatetags.static import static
from django.utils.html import format_html

from wagtail import hooks


@hooks.register("insert_global_admin_js", order=100)
def global_admin_js():
    """Add /static/js/admin/easymde_custom.js to the admin."""
    return format_html('<script src="{}"></script>', static("js/easymde_custom.js"))

Inline links

wagtail-markdown supports custom inline links syntax:

Link to Syntax Notes
Pages [title](page:PAGE_ID) PAGE_ID is the page ID
Documents [title](doc:DOCUMENT_ID) DOCUMENT_ID is the document ID
Media [title](media:MEDIA_ID) Needs wagtailmedia. MEDIA_ID is the media item ID
Images ![alt text](image:IMAGE_ID) Renders an image tag. IMAGE_ID is the image ID
↳ with class attribute ![alt text](image:IMAGE_ID,class=the-class-name) adds class="the-class-name" to the ` tag
↳ with rendition filter ![alt text](image:IMAGE_ID,filter=fill-200x200&#x7c;format-webp) Uses the same format as generating renditions in Python
↳ class name and filter can be stacked ![alt text](image:IMAGE_ID,class=the-class-name,filter=width-100)

Previously we supported custom link tags that used the target object title. They had the following form:

  • <:My page name|link title> or <:page:My page title>
  • <:doc:My fancy document.pdf>
  • <:image:My pretty image.jpeg>, <:image:My pretty image.jpeg|left> (left classname), <:image:My pretty image.jpeg|right> (right classname), <:image:My pretty image.jpeg|full> (full-name classname), <:image:My pretty image.jpeg|width=123> (outputs a rendition with width-123, and class left)

⚠️ these types of tags are not reliable as titles can and will change. Support for will be removed in the future.

Usage

You can use it as a StreamField block:

from wagtail.blocks import StreamBlock

from wagtailmarkdown.blocks import MarkdownBlock


class MyStreamBlock(StreamBlock):
    markdown = MarkdownBlock(icon="code")
    # ...

Or use as a page field:

from wagtail.admin.panels import FieldPanel
from wagtail.models import Page

from wagtailmarkdown.fields import MarkdownField


class MyPage(Page):
    body = MarkdownField()

    content_panels = [
        FieldPanel("title", classname="full title"),
        FieldPanel("body"),
    ]

And render the content in a template:

{% load wagtailmarkdown %}
<article>
{{ self.body|markdown }}
</article>

Compatibility

wagtail-markdown supports Wagtail 4.1 and above, python-markdown 3.3 and above.

Contributing

All contributions are welcome!

Installation

To make changes to this project, first clone this repository:

git clone [email protected]:torchbox/wagtail-markdown.git
cd wagtail-markdown

With your preferred Python virtual environment activated, install testing dependencies:

pip install -e '.[testing]' -U

pre-commit

Note that this project uses pre-commit. To set up locally:

# if you don't have it yet
$ pip install pre-commit
# go to the project directory
$ cd wagtail-markdown
# initialize pre-commit
$ pre-commit install

# Optional, run all checks once for this, then the checks will run only on the changed files
$ pre-commit run --all-files

How to run tests

To run all tests in all environments:

tox -p

To run tests for a specific environment:

tox -e py312-django5.0-wagtail6.0

or, a specific test

tox -e py312-django5.0-wagtail6.0 -- tests.testapp.tests.test_admin.TestFieldsAdmin

wagtail-markdown's People

Contributors

abrunyate avatar bashu avatar benjaoming avatar bjackson avatar danihodovic avatar drockolla avatar elcuy avatar frcroth avatar jcuotpc avatar johnfraney avatar juyrjola avatar katdom13 avatar kevinhowbrook avatar nickmoreton avatar pre-commit-ci[bot] avatar ramonakira avatar rokdd avatar rspeed avatar stefanulbrich avatar stormheg avatar stuaxo avatar tm-kn avatar unixwitch avatar vegaelle avatar zerolab 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  avatar  avatar  avatar  avatar  avatar

wagtail-markdown's Issues

ImportError: cannot import name 'MarkdownField'

Trying to use this (mediafix branch) with the wagtail demo installation and getting this error:

[wagtaildemo wagtaildemo]$ ./manage.py runserver 0.0.0.0:8000
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/vagrant/.virtualenvs/wagtaildemo/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/vagrant/.virtualenvs/wagtaildemo/lib/python3.4/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/home/vagrant/.virtualenvs/wagtaildemo/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/vagrant/.virtualenvs/wagtaildemo/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/home/vagrant/.virtualenvs/wagtaildemo/lib/python3.4/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/vagrant/wagtaildemo/demo/models.py", line 28, in <module>
    from wagtailmarkdown import MarkdownField, MarkdownPanel
ImportError: cannot import name 'MarkdownField'

On the master branch I was running into a similar issue as this:

#6

PyPi updates

I don't have permission to update pypi and we need to update the package.
@tm-kn could you add me or build a new dist.
Thanks

Package needs building for PyPi

Markdown field in Wagtail Admin 3.0

Issue Summary

I use wagtail markdown. I've recently upgraded my sites to Wagtail 3.0.1. If I use the admin to edit my page content the wagtail markdown field is blank until I click on the empty box which is when it then appears.

Steps to Reproduce

  1. Use admin to edit a page that has a wagtail markdown field.
  2. It is blank for me until I click on the empty field

Any other relevant information. For example, why do you consider this a bug and what did you expect to happen instead?

  • I have confirmed that this issue can be reproduced as described on a fresh Wagtail project: (no - occurred after an upgrade)

Technical details

  • Python version: Run python --version. 3.8.10
  • Django version: Look in your requirements.txt, or run pip show django | grep Version. 3.2.13
  • Wagtail version: Look at the bottom of the Settings menu in the Wagtail admin, or run pip show wagtail | grep Version:. 3.0.1
  • Browser version: You can use https://www.whatsmybrowser.org/ to find this out. Chrome 102 plus Firefox

How to populate a portion of post in markdown format into post list

I am using Wagtail along with wagtail-markdown, and I have a list of posts all in Markdown Format.

### HTML template file,  Post_List.html ###
{% extends 'Base_Layout.html' %}
{% load wagtailcore_tags wagtailroutablepage_tags debugger_tags comments wagtailmarkdown %}

{% block main %}
{% page|pdb %}
    <main>
        {% for post in page.posts %}
   </main>
{% endblock %}

(Pdb++) pp obj.posts[1].body|markdown
*** NameError: name 'markdown' is not defined
(Pdb++) pp type(obj.posts[1].body)
<class 'str'>
(Pdb++) pp obj.posts[1].body[:100]

obj.posts[1].body is a string in raw markdown format.

I tried <p>{{post.body|markdown.getElementsByTagName("P")[0]}}</p>, but it failed with below error Could not parse the remainder: '.getElementsByTagName("P")[0]' from 'post.body|markdown.getElementsByTagName("P")[0]'.

Q1: In the HTML template of Post List, how can I capture a portion of a specific post in Markdown format, and populate that into the post list webpage?

Q2: How can I get the first image from the raw markdown content and populate into the post list html file?

App Load Order?

Not sure where this is coming from... possibly django 1.9

File "/Users/rob/Sites/moggach/apps/wagtailmarkdown/__init__.py", line 16, in <module>
  from wagtail.wagtailcore.blocks import TextBlock
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/wagtail/wagtailcore/blocks/__init__.py", line 5, in <module>
  from .field_block import *  # NOQA
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/wagtail/wagtailcore/blocks/field_block.py", line 15, in <module>
  from wagtail.wagtailcore.rich_text import RichText
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/wagtail/wagtailcore/rich_text.py", line 10, in <module>
  from wagtail.wagtailcore.models import Page
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/wagtail/wagtailcore/models.py", line 9, in <module>
  from modelcluster.models import ClusterableModel, get_all_child_relations
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/modelcluster/models.py", line 152, in <module>
  class ClusterableModel(models.Model):
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__
  app_config = apps.get_containing_app_config(module)
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
  self.check_apps_ready()
File "/Users/rob/.virtualenvs/wagtail/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
  raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Link by primary key

It would be nice to be able to reference by image/page id instead of title since the titles can be changed

Missing requirement

When I install wagtail-markdown I get an error because pyparsing is not listed in the requirements:

~/work/royal_orchard$ pip install git+https://github.com/torchbox/wagtail-markdown.git
Collecting git+https://github.com/torchbox/wagtail-markdown.git
  Cloning https://github.com/torchbox/wagtail-markdown.git to /tmp/pip-oke7k_rs-build
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/jmv/.virtualenvs/rolc/lib/python3.5/site-packages/setuptools/__init__.py", line 12, in <module>
        import setuptools.version
      File "/home/jmv/.virtualenvs/rolc/lib/python3.5/site-packages/setuptools/version.py", line 1, in <module>
        import pkg_resources
      File "/home/jmv/.virtualenvs/rolc/lib/python3.5/site-packages/pkg_resources/__init__.py", line 72, in <module>
        import packaging.requirements
      File "/home/jmv/.virtualenvs/rolc/lib/python3.5/site-packages/packaging/requirements.py", line 9, in <module>
        from pyparsing import stringStart, stringEnd, originalTextFor, ParseException
    ImportError: No module named 'pyparsing'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-oke7k_rs-build/

Also, is it possible to upload the package to PyPI, please?

Set up CI

Set up CI for both Python 2 and Python 3, preferably using tox. Most likely it'd be good to test against a few recent versions of Wagtail.

trouble with bleach

I'm deploying on Heroku using python 3.6.3
but I'm getting an error:

   Collecting wagtail-markdown==0.4.1 (from -r /tmp/build_e2d694b32c1dc181c4b75586ee858300/requirements.txt (line 49))
     Could not find a version that satisfies the requirement wagtail-markdown==0.4.1 (from -r /tmp/build_e2d694b32c1dc181c4b75586ee858300/requirements.txt (line 49)) (from versions: )
   No matching distribution found for wagtail-markdown==0.4.1 (from -r /tmp/build_e2d694b32c1dc181c4b75586ee858300/requirements.txt (line 49))

when I run
pip install wagtail-markdown && pip freeze > requirements.txt

It downgrades my Bleach from version 2.1.1 to version 1.4.2, which breaks my html5lib.sanitizer
I tried to upgrade bleach to fix that, as shown here:
ckan/ckan#3257

Then when requirements are installed on deployment Bleach gets downgraded automatically due to wagtail-markdown's requirements. Can we bump up the bleach requirement here?

FontAwesome is a dependency

FontAwesome as a dependency needs to be documented or maybe a subset webfont should be created to meet the needs of the UI and put in the static media as appropriate.

Toggle edit controls to hide raw markdown ?

I like markdown as a data format, but for non-technical users of my website it's confusing.

Is it possible hide the options on the editor that display markdown.

On my own site, I'd put this behind a permission so that superusers could still see markdown.

`allowed_attributes` settings wipes out default `allowed_attributes` unexpectedly.

by default, allowed_attributes for <img> are ["src", "alt"].
When I configure my settings.py as below,

WAGTAILMARKDOWN = {
    "allowed_attributes": {"img": ["title"] 
                            },  
}

Based on the source code wagtailmarkdown/utils.py

if "allowed_attributes" in settings.WAGTAILMARKDOWN:
            bleach_kwargs["attributes"] = {
                **bleach_kwargs["attributes"],
                **settings.WAGTAILMARKDOWN["allowed_attributes"],
            }

Newly added allowed_attributes should be added on top of default allowed_attributes. However, based on my testing here, default allowed_attributes are wiped out and the resulted <img> only has attributetitle=" " now.

'<p><img title=" "></p>\n'
'<p><img title=" "></p>\n'

problem can be solved by including default allowed_attributes in the settings.py configurations.

WAGTAILMARKDOWN = {
    "allowed_attributes": {"img": ["title", "src", "alt"] 
                            },  
}

It is a minor issue, but since I experienced it, just share with the team.

Inline link to documents is broken

I tried the inline link to documents (<:doc:My fancy document.pdf>) but it is broken.
ImportError: cannot import name 'wagtaildocs' from 'wagtail'

I believe a fix needs to be made in the module wagtailmarkdown.mdx.linkers.document:

The follwing code at line 13:

from wagtail import wagtaildocs

should be replaced with:

try:  # wagtail < 2.0
    from wagtail.wagtaildocs.models import Document
except ImportError:  # wagtail >= 2.0
    from wagtail.documents.models import Document

and line 25 should be changed to:

doc = Document.objects.get(title=name)

RFC - page linking.

The current tag for linking pages, links by Title obviously there is the danger of clashes, is it worth making it possible to link by id or slug ?

I wonder if it's worth adding some error checking for broken links to pages in the admin interface too ?

(Obviously ideally the editor would know about the page chooser - but this might be tricky, I guess there could be something to handle pages moving / changing too, but again, a bit tricky)

TemplateSyntaxError: 'wagtailmarkdown' is not a valid tag library: ImportError raised loading wagtailmarkdown.templatetags.wagtailmarkdown: No module named utils

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
...
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/django/template/base.py", line 342, in parse
    compiled_result = compile_func(self, token)
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/django/template/defaulttags.py", line 1163, in load
    (taglib, e))
TemplateSyntaxError: 'wagtailmarkdown' is not a valid tag library: ImportError raised loading wagtailmarkdown.templatetags.wagtailmarkdown: No module named utils

Custom extensions in MarkdownBlock

Sorry for asking more but I am a big fan of markdown and it's system. So I thought it is worth to implement a icon library and implementented into the extensions (and this works):

WAGTAILMARKDOWN_EXTENSIONS = ["toc", "sane_lists",'home.extensions.iconfonts:IconFontsExtension']

But in the markdown it does not handle the result safe:
grafik

As you can see the other markdowns for bold text was working. So do I something wrong? What is the best way to fix..? The MarkdownBlock in a Streamfield so I can not set it safe in the template.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
...
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/wagtailmarkdown/templatetags/wagtailmarkdown.py", line 20, in markdown
    return render_markdown(value)
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/wagtailmarkdown/utils.py", line 27, in render_markdown
    markdown_html = _transform_markdown_into_html(text)
  File "/home/vagrant/.virtualenv/local/lib/python2.7/site-packages/wagtailmarkdown/utils.py", line 33, in _transform_markdown_into_html
    return markdown.markdown(str(text), **_get_markdown_kwargs())
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

Markdown without the paragraph tag ?

Text from the |markdown seems to be wrapped in <p> tags, is there any way around this ?

I'm using some markdown for a single line bit of text, but the <p> needs css to workaround.

Create PyPI package

Hi, could you upload a PyPI package? I want to include this package on the next Puput release.

thanks

Customized toolbar based on var

Some time ago customized the “original version” of wagtail markdown to alter the tool in the toolbar based on a variable.

Due to changes in wagtail markdown these customizations no longer work anymore.

But maybe there is some interest in the code?

Cheers,

Rob

Add support for general `FieldPanel` with Wagtail 3.0+

References:

Where possible, third-party packages that implement their own field panel types should be updated to allow using a plain FieldPanel instead, in line with Wagtail dropping its own special-purpose field panel types such as StreamFieldPanel and ImageChooserPanel. The steps for doing this will depend on the package’s functionality, but in general:

  • If the panel sets a custom template, your code should instead define a Widget class that produces your desired HTML rendering.
  • If the panel provides a widget_overrides method, your code should instead call register_form_field_override so that the desired widget is always selected for the relevant model field type.
  • If the panel provides a get_comparison_class method, your code should instead call wagtail.admin.compare.register_comparison_class to register the comparison class against the relevant model field type.

license

Could you please add license to this package.

Add br

To allow line breaks ussing a double space add 'br' to tags in utils.render.

tags = [ 'br', 'p', 'div',etc ],

online video embedding support

does it support online video embedding ? if yes, what is the syntax to embed online video in markdown.
I have tried <video> and <iframe>, all failed, after markdown rendering, they are all displayed as plain text as if Markdown parser does not understand them at all.

<iframe style='width: 600px;height: 338px' frameborder='no' allowfullscreen mozallowfullscreen webkitallowfullscreen src='http://online_video_url'></iframe>

<video controls preload="metadata" width="100%">
<source src="online_video_url" type="video/mp4"> </video>

MarkdownBlock Empty after saving in Wagtail 2.13

After press "Save draft" the content of the MarkdownBlock disappears (also for publishing). When I publish direct in one step it publishes the content, but I cannot edit, because the textarea is blank afterwards.

    body = StreamField([
        ('heading', blocks.CharBlock(form_classname="full title")),
        ('paragraph', blocks.RichTextBlock(required=False)),
        ('image', ImageChooserBlock()),
        ('image_wide', MyWideImage()),
        ('text',MarkdownBlock())],
        blank=True)
# ...
   content_panels = Page.content_panels + [
# ...
        StreamFieldPanel('body'),
# ...
    ]

I am new to wagtail and just start the first project, so when I could send something for debug let me know! Migrate I runned..

I am using: python 3.9 + django 3.2.3 + wagtail 2.13 + wagtail-markdown 0.6
(tried also with wagtail-markdown v0.7.0-rc1)

Update: I checked the database and the value is written correctly. So I assume it is a problem with reading the value:
, {"type": "text", "value": "ds\r\nds\r\nds\r\nds\r\nds\r\nds\r\nds\r\nd\r\nds\r\nds\r\nds", "id": "77faf527-1d4c-45ec-bf42-456a18724590"}]

This project needs a maintainer.

Hi,

This repository seems to lack maintenance, I propose myself as a new maintainer.

Could you give me the right to push in your repository or just transfer it on my account in github?

Thank you

Lack of detailed document for configuration

I am installing and configuring wagtail-markdown, in the github page, it reads:

settings.py

WAGTAILMARKDOWN = {
"autodownload_fontawesome": False,
"allowed_tags": [], # optional. a list of tags
"allowed_styles": [], # optional. a list of styles
"allowed_attributes": {}, # optional. a dict with HTML tag as key and a list of attributes as value
"extensions": [], # optioanl. a list of extensions
"extension_configs": {}, # optional. a dictionary with the extension name as key, and its configuration as value
}

However, I did not find any documents answering below questions:

  1. what tags can be put in "allowed_tags": [] and in what format "allowed_tags": ["tag#1", "tag#2", "tag#3"] ?
  2. what extensions are supported ?
  3. what are default values for all those configuration options, default value for [] and {} is blank ?

SimpleMDE ReferenceError: Can't find variable: simplemdeAttach

Wagtail: 1.3.1 version
wagtail-markdown installed with:pip -e git+https://github.com/torchbox/wagtail-markdown.git#egg=wagtail_markdown

Then

...
from wagtailmarkdown import MarkdownBlock
...
class BlogBodyStreamBlock(StreamBlock):
    intro = RichTextBlock(icon="pilcrow")
     ...
    markdown = MarkdownBlock(icon="code")

class BlogPage(Page):
    body = StreamField(BlogBodyStreamBlock)
    content_panels = Page.content_panels + [
        ...
        StreamFieldPanel('body'),
    ]

In admin interface no MDE editor, and got error in JS console:
🪲 _"ReferenceError: Can't find variable: simplemdeAttach"_

In other panel

When placed in another panel:

promote_panels = [
MarkdownPanel("summary"),
]

In edit mode the content is only displayed after the field get’s focus.

Best regards,
– Robert

Code refactor

Hi,
I realized that there are some PEP 8 mistakes, camel case naming and pylint warnings. Maybe you could execute flake8 on the code and fix some issues.

Add support for Django 2.2 and Wagtail 2.6.1

Currently, the latest version of Wagtail is 2.6.1.
The latest version of Django is 2.2.4.
However, it seems that the current version does not support at least Wagtail 2.6.1.
When I tried to install it in my project, it failed.

For reference, I attach the Pipfile used in my project.

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
flake8 = "*"

[packages]
wagtail = "<2.7,>=2.6"
Django = "==2.1.7"
django-storages = "*"
zappa-django-utils = "*"
awscli = "*"
python-dotenv = "*"
zappa = "*"
mysqlclient = "*"
django-s3-storage = "*"
wagtail-graphql = "*"
django-debug-toolbar = "*"

[requires]
python_version = "3.6"

Please respond to the latest version.

Customise SimpleMDE options?

Hi all, and thank you Torchbox!

Is it possible to customise the SimpleMDE configuration like this? I would like to hide some icons and disable spell checking.

I can access /static/wagtailmarkdown/js/simplemde.attach.js and modify options during the creation of the new SimpleMDE() but nothing seems to apply. If I try console.log('test') in this file I also can't see the log, so I'm assuming this file isn't what is being read when editing my pages in Wagtail, however the debugger says my browser is pulling this exact file:

image

Any help would be greatly appreciated! Thank you.

HTML renderred by wagtail-markdown is not recoginzed as HTML contents by browser

I am using Wagtail + Wagtail_markdown to support editing blog post using markdown.
In order to save the CPU for rendering markdown to HTML every time when blog post is viewed by internet end users, I will save both Markdown (for editing) and HTML (for viewing by end users) version in DB.

Based in the wagtail_markdown source code of template filter as below.

@register.filter(name="markdown")
def markdown(value):
   return render_markdown(value)

I override the default page.save() in App/models.py.

in App/models.py

from wagtailmarkdown.utils import render_markdown

class PostDetail(Page):
    template = "Post_Detail.html"
    
    body = MarkdownField()
    html_body = models.TextField(editable=False, default="Empty")

    def save(self, html_body=None, *args, **kwargs):
        self.html_body = render_markdown(self.body)
        return super().save(*args, **kwargs)

in template file: Post_Detail.html

{% load wagtailmarkdown %}

<div class="markdown">
      {{ page.html_body }}   ## It was working perfectly if I replaced this row with '{{ page.body | markdown  }}'
</div>

After inspect elements in browser, I can see HTML content within <div class="markdown">. However, those HTML contents seems not understood by browser at all, because they are displayed as raw text string along with HTML tags. On the webpage, you will see paragraph contents as below:

<p>this is the first paragraph of this blog post</p>
<p><img alt="pic_name" src="http://abc.com/ZIP.jpeg"></p>
<p>this is the second paragraph of this blog post</p>

and they are not styled according to my CSS file either.

Anything I missed out ??

Static files for simplemde missing from PyPI

[27/Dec/2017 08:47:50] "GET /static/wagtailmarkdown/js/simplemde.attach.js HTTP/1.1" 404 1841
[27/Dec/2017 08:47:50] "GET /static/wagtailmarkdown/js/simplemde.min.js HTTP/1.1" 404 1832
[27/Dec/2017 08:47:50] "GET /static/wagtailmarkdown/js/simplemde.min.js HTTP/1.1" 404 1832
[27/Dec/2017 08:47:50] "GET /static/wagtailmarkdown/js/simplemde.attach.js HTTP/1.1" 404 1841

I could resolve this with: pipenv install git+https://github.com/torchbox/wagtail-markdown.git#egg=wagtail-markdown

Perhaps, a new build should be uploaded to PyPI.

Expected UI issues with Wagtail 3.0 release

The Wagtail 3.0 first release candidate is out. There are large UI changes in this release, for which we have reviewed expected breakage in third-party UI customisations.

This is beyond what we do with our normal breaking changes policy, since the majority of those changes are on parts of Wagtail that haven’t been publicly supported / documented in any way. To make sure this goes smoothly anyway, I’m here to provide an advance notice of what we’re aware of with this specific package 🙂

There’s only one thing – apparently this package relies on Wagtail’s tabs implementation, which has been removed. Here are the results of our code search:

torchbox/wagtail-markdown/wagtailmarkdown/static/wagtailmarkdown/js/easymde.attach.js
43:$(document).on('shown.bs.tab', function(e) {

This will likely need investigation and rework. From what I understand of this code, this type of customisation still remains unsupported – if we need to make changes in Wagtail so there is an official API for this, please request this via GitHub issues.

Invalid filter: 'markdown'

I followed the instructions but get an exception during page render, is there some extra config needed?

Invalid filter: 'markdown'
Request Method: GET
Request URL:    http://127.0.0.1:8000/testing/
Django Version: 1.8.5
Exception Type: TemplateSyntaxError
Exception Value:    
Invalid filter: 'markdown'
Exception Location: /usr/local/lib/python2.7/site-packages/django/template/base.py in find_filter, line 429
Python Executable:  /usr/local/opt/python/bin/python2.7
Python Version: 2.7.9
Python Path:    
['/Users/jan/mysite',
 '/Library/Frameworks/SQLite3.framework/Versions/C/Python/2.7',
 '/Library/Frameworks/GEOS.framework/Versions/3/Python/2.7',
 '/Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.7/site-packages',
 '/usr/local/lib/python2.7/site-packages/setuptools-15.0-py2.7.egg',
 '/usr/local/lib/python2.7/site-packages/wagtail_markdown-0.3.2-py2.7.egg',
 '/usr/local/lib/python2.7/site-packages/bleach-1.4.2-py2.7.egg',
 '/usr/local/lib/python2.7/site-packages/Markdown-2.6.2-py2.7.egg',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/Users/jan/Library/Python/2.7/lib/python/site-packages',
 '/usr/local/lib/python2.7/site-packages',
 '/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg',
 '/Library/Python/2.7/site-packages']
Server time:    Wed, 7 Oct 2015 16:12:41 +0000

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I am getting this exception right after I place the 'wagtailmarkdown' in INSTALLED_APPS list in the config file.
Am I doing something wrong?

Here is the full stack trace

manage.py@blogtest > makemigrations
bash -cl "/opt/pydev/wtblog/env/bin/python /opt/pycharm-2016.3.2/helpers/pycharm/django_manage.py makemigrations /opt/pydev/wtblog/blogtest"
Traceback (most recent call last):
  File "/opt/pycharm-2016.3.2/helpers/pycharm/django_manage.py", line 41, in <module>
    run_module(manage_file, None, '__main__', True)
  File "/usr/lib64/python3.4/runpy.py", line 182, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/usr/lib64/python3.4/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/lib64/python3.4/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/opt/pydev/wtblog/blogtest/manage.py", line 12, in <module>
    execute_from_command_line(sys.argv)
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/lib64/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/wagtail_markdown-0.4.1-py3.4.egg/wagtailmarkdown/__init__.py", line 16, in <module>
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/wagtail/wagtailcore/blocks/__init__.py", line 5, in <module>
    from .field_block import *  # NOQA
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/wagtail/wagtailcore/blocks/field_block.py", line 16, in <module>
    from wagtail.wagtailcore.rich_text import RichText
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/wagtail/wagtailcore/rich_text.py", line 10, in <module>
    from wagtail.wagtailcore.models import Page
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/wagtail/wagtailcore/models.py", line 9, in <module>
    from django.contrib.auth.models import Group, Permission
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/contrib/auth/models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/contrib/auth/base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/opt/pydev/wtblog/env/lib64/python3.4/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
$ pip freeze
appdirs==1.4.0
beautifulsoup4==4.5.3
bleach==1.5.0
dj-database-url==0.3.0
Django==1.10.5
django-appconf==1.0.2
django-compressor==2.1
django-libsass==0.7
django-modelcluster==3.0.1
django-redis==3.8.2
django-taggit==0.22.0
django-treebeard==4.1.0
djangorestframework==3.5.4
elasticsearch==1.2.0
html5lib==0.9999999
libsass==0.8.2
Markdown==2.6.2
olefile==0.44
packaging==16.8
Pillow==4.0.0
Pygments==2.2.0
pyparsing==2.1.10
pytz==2016.10
rcssmin==1.0.6
redis==2.10.5
requests==2.13.0
rjsmin==1.0.12
six==1.10.0
Unidecode==0.4.20
urllib3==1.19.1
wagtail==1.9
wagtail-markdown==0.4.1
webencodings==0.5
whitenoise==3.2.3
Willow==0.4

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.