django-markdownfield


Namedjango-markdownfield JSON
Version 0.11.0 PyPI version JSON
download
home_pagehttps://github.com/dmptrluke/django-markdownfield
SummaryA simple custom field for Django that can safely render Markdown and store it in the database.
upload_time2023-08-27 04:00:44
maintainerNone
docs_urlNone
authorLuke Rogers
requires_python>=3.8
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # django-markdownfield  [![PyPI](https://img.shields.io/pypi/v/django-markdownfield)](https://pypi.org/project/django-markdownfield/)
A simple custom field for Django that can safely render Markdown and store it in the database.

Your text is stored in a `MarkdownField`. When the model is saved, django-markdownfield will
parse the Markdown, render it, sanitise it with [bleach](https://github.com/mozilla/bleach), and store
the result in a `RenderedMarkdownField` for display to end users.

django-markdownfield also bundles a minified version of the [EasyMDE](https://github.com/Ionaru/easy-markdown-editor)
editor (v2.14.0) in admin views to make working with Markdown easier.

![alt test](https://raw.githubusercontent.com/dmptrluke/django-markdownfield/master/screenshots/editor.png)

## Installation

django-markdownfield can be installed from PyPi:

```console
# Install directly or add to your requirements.txt
pip install django-markdownfield
```

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

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

## Usage

Implementing django-markdownfield is simple. See the below example.


```python
from django.db import models

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

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

Please also set `SITE_URL` in your Django configuration - it will be needed for detecting
external links.

```python
SITE_URL = "https://example.com"
```

To disable the EasyMDE editor, see the amended line below.

```python
text = MarkdownField(rendered_field='text_rendered', use_editor=False, use_admin_editor=True)
```

### Use in templates

To use the rendered markdown in templates, just use the `RenderedMarkdownField()` you created on
your model, like below. This field should be marked as safe with the `safe` filter to ensure it
displays correctly.

```djangotemplate
{{ post.text_rendered | safe }}
```

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

### VALIDATOR_STANDARD
```python
from markdownfield.validators import VALIDATOR_STANDARD
```
This validator strips any tags that are not used by standard Markdown. It also automatically links
any URLs in the output, adding `class="external"`, `rel="nofollow noopener noreferrer"`, and
`target="_blank"` to any URLs which it determines to be external.

### VALIDATOR_CLASSY
```python
from markdownfield.validators import VALIDATOR_CLASSY
```
This validator does much the same as `VALIDATOR_STANDARD`, but it allows you to set the class on
links and images. This is useful to create buttons and other enhanced links.

### VALIDATOR_NULL
```python
from markdownfield.validators import VALIDATOR_NULL
```
This validator does not call [bleach](https://github.com/mozilla/bleach) to sanitize the output at all.
This is **not safe for user input**.  It allows arbitrary (unsafe) HTML in your markdown input.


### Creating Custom Validators
To create a custom validator, just create an instance of  the `markdownfield.validators.Validator`
dataclass. An example of this is shown below.

```python
from markdownfield.validators import Validator

# allows only bold and italic text
VALIDATOR_COMMENTS = Validator(
    allowed_tags=["b", "i", "strong", "em"],
    allowed_attrs={},
    linkify=False
)
```

You can also find a standard set of markdown-safe tags and attrs in `markdownfield.validators`, and extend
that.

```python
from markdownfield.validators import Validator, MARKDOWN_TAGS, MARKDOWN_ATTRS

# allows all standard markdown features,
# but also allows the class to be set on images and links
VALIDATOR_CLASSY = Validator(
    allowed_tags=MARKDOWN_TAGS,
    allowed_attrs={
        **MARKDOWN_ATTRS,
        'img': ['src', 'alt', 'title', 'class'],
        'a': ['href', 'alt', 'title', 'name', 'class']
    }
)
```

## Migrations

If you need to migrate from TextField or CharField to the MarkdownField you need to migrate the stored `text` also in the `rendered_text` field.
Update your auto-created migration fiele and add the method below. 
Use a method to `save()` every instance of your model once after the migrations, so the text will be copied into the `text_rendered` field correctly.

```python
from django.db import migrations
import markdownfield.models


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


class Migration(migrations.Migration):

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

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

## License

This software is released under the MIT license.
```
Copyright (c) 2019-2021 Luke Rogers

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

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

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

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/dmptrluke/django-markdownfield",
    "name": "django-markdownfield",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Luke Rogers",
    "author_email": "luke@dmptr.com",
    "download_url": "https://files.pythonhosted.org/packages/3d/ee/7244016bef5911fa10aa983af9237c2e6e546ba76561ad57a3c5a95a9aff/django_markdownfield-0.11.0.tar.gz",
    "platform": null,
    "description": "# django-markdownfield  [![PyPI](https://img.shields.io/pypi/v/django-markdownfield)](https://pypi.org/project/django-markdownfield/)\nA simple custom field for Django that can safely render Markdown and store it in the database.\n\nYour text is stored in a `MarkdownField`. When the model is saved, django-markdownfield will\nparse the Markdown, render it, sanitise it with [bleach](https://github.com/mozilla/bleach), and store\nthe result in a `RenderedMarkdownField` for display to end users.\n\ndjango-markdownfield also bundles a minified version of the [EasyMDE](https://github.com/Ionaru/easy-markdown-editor)\neditor (v2.14.0) in admin views to make working with Markdown easier.\n\n![alt test](https://raw.githubusercontent.com/dmptrluke/django-markdownfield/master/screenshots/editor.png)\n\n## Installation\n\ndjango-markdownfield can be installed from PyPi:\n\n```console\n# Install directly or add to your requirements.txt\npip install django-markdownfield\n```\n\nAfter installation, you need to add `markdownfield` to `INSTALLED_APPS` of your Django project's settings.\n\n```python\nINSTALLED_APPS = [\n    \"markdownfield\",\n    ...\n    \"django.contrib.staticfiles\",\n]\n```\n\n## Usage\n\nImplementing django-markdownfield is simple. See the below example.\n\n\n```python\nfrom django.db import models\n\nfrom markdownfield.models import MarkdownField, RenderedMarkdownField\nfrom markdownfield.validators import VALIDATOR_STANDARD\n\nclass Page(models.Model):\n    text = MarkdownField(rendered_field='text_rendered', validator=VALIDATOR_STANDARD)\n    text_rendered = RenderedMarkdownField()\n```\n\nPlease also set `SITE_URL` in your Django configuration - it will be needed for detecting\nexternal links.\n\n```python\nSITE_URL = \"https://example.com\"\n```\n\nTo disable the EasyMDE editor, see the amended line below.\n\n```python\ntext = MarkdownField(rendered_field='text_rendered', use_editor=False, use_admin_editor=True)\n```\n\n### Use in templates\n\nTo use the rendered markdown in templates, just use the `RenderedMarkdownField()` you created on\nyour model, like below. This field should be marked as safe with the `safe` filter to ensure it\ndisplays correctly.\n\n```djangotemplate\n{{ post.text_rendered | safe }}\n```\n\n## Validators\ndjango-markdownfield comes with a number of validators, which are used to process and clean\nthe output of the markdown engine\n\n### VALIDATOR_STANDARD\n```python\nfrom markdownfield.validators import VALIDATOR_STANDARD\n```\nThis validator strips any tags that are not used by standard Markdown. It also automatically links\nany URLs in the output, adding `class=\"external\"`, `rel=\"nofollow noopener noreferrer\"`, and\n`target=\"_blank\"` to any URLs which it determines to be external.\n\n### VALIDATOR_CLASSY\n```python\nfrom markdownfield.validators import VALIDATOR_CLASSY\n```\nThis validator does much the same as `VALIDATOR_STANDARD`, but it allows you to set the class on\nlinks and images. This is useful to create buttons and other enhanced links.\n\n### VALIDATOR_NULL\n```python\nfrom markdownfield.validators import VALIDATOR_NULL\n```\nThis validator does not call [bleach](https://github.com/mozilla/bleach) to sanitize the output at all.\nThis is **not safe for user input**.  It allows arbitrary (unsafe) HTML in your markdown input.\n\n\n### Creating Custom Validators\nTo create a custom validator, just create an instance of  the `markdownfield.validators.Validator`\ndataclass. An example of this is shown below.\n\n```python\nfrom markdownfield.validators import Validator\n\n# allows only bold and italic text\nVALIDATOR_COMMENTS = Validator(\n    allowed_tags=[\"b\", \"i\", \"strong\", \"em\"],\n    allowed_attrs={},\n    linkify=False\n)\n```\n\nYou can also find a standard set of markdown-safe tags and attrs in `markdownfield.validators`, and extend\nthat.\n\n```python\nfrom markdownfield.validators import Validator, MARKDOWN_TAGS, MARKDOWN_ATTRS\n\n# allows all standard markdown features,\n# but also allows the class to be set on images and links\nVALIDATOR_CLASSY = Validator(\n    allowed_tags=MARKDOWN_TAGS,\n    allowed_attrs={\n        **MARKDOWN_ATTRS,\n        'img': ['src', 'alt', 'title', 'class'],\n        'a': ['href', 'alt', 'title', 'name', 'class']\n    }\n)\n```\n\n## Migrations\n\nIf you need to migrate from TextField or CharField to the MarkdownField you need to migrate the stored `text` also in the `rendered_text` field.\nUpdate your auto-created migration fiele and add the method below. \nUse a method to `save()` every instance of your model once after the migrations, so the text will be copied into the `text_rendered` field correctly.\n\n```python\nfrom django.db import migrations\nimport markdownfield.models\n\n\ndef save_text_rendered(apps, schema_editor):\n    ExampleModel = apps.get_model('yourapp', 'ExampleModel')\n    for examplemodel in ExampleModel.objects.all():\n        examplemodel.save()\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('yourapp', '000X_migrate_to_markdownfield'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name='yourapp',\n            name='text_rendered',\n            field=markdownfield.models.RenderedMarkdownField(default=''),\n            preserve_default=False,\n        ),\n        migrations.AlterField(\n            model_name='ExampleModel',\n            name='text',\n            field=markdownfield.models.MarkdownField(rendered_field='text_rendered'),\n        ),\n        migrations.RunPython(save_text_rendered),\n    ]\n```\n\n## License\n\nThis software is released under the MIT license.\n```\nCopyright (c) 2019-2021 Luke Rogers\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A simple custom field for Django that can safely render Markdown and store it in the database.",
    "version": "0.11.0",
    "project_urls": {
        "Homepage": "https://github.com/dmptrluke/django-markdownfield"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e636d7a13624668f3ae5a9abb9b253ad14b775f1140f4055b1b5870a582de15b",
                "md5": "965d58523f215889c0d0f6b6d7379a0e",
                "sha256": "fc9d60b4dbb846954ec05832c28400f138303e02d309316a105b9e1b9182183d"
            },
            "downloads": -1,
            "filename": "django_markdownfield-0.11.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "965d58523f215889c0d0f6b6d7379a0e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 745902,
            "upload_time": "2023-08-27T04:00:36",
            "upload_time_iso_8601": "2023-08-27T04:00:36.758546Z",
            "url": "https://files.pythonhosted.org/packages/e6/36/d7a13624668f3ae5a9abb9b253ad14b775f1140f4055b1b5870a582de15b/django_markdownfield-0.11.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3dee7244016bef5911fa10aa983af9237c2e6e546ba76561ad57a3c5a95a9aff",
                "md5": "04d86f8dafbf6745f5cfb81c08b6ed4f",
                "sha256": "6f1636b21226b658a18a9bc3d5284a8708447fe3d772b933c65fec9f28d119b9"
            },
            "downloads": -1,
            "filename": "django_markdownfield-0.11.0.tar.gz",
            "has_sig": false,
            "md5_digest": "04d86f8dafbf6745f5cfb81c08b6ed4f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 779982,
            "upload_time": "2023-08-27T04:00:44",
            "upload_time_iso_8601": "2023-08-27T04:00:44.330094Z",
            "url": "https://files.pythonhosted.org/packages/3d/ee/7244016bef5911fa10aa983af9237c2e6e546ba76561ad57a3c5a95a9aff/django_markdownfield-0.11.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-27 04:00:44",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "dmptrluke",
    "github_project": "django-markdownfield",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "django-markdownfield"
}
        
Elapsed time: 0.11588s