wagtailmedia


Namewagtailmedia JSON
Version 0.15.1 PyPI version JSON
download
home_page
SummaryA Wagtail module for audio and video files.
upload_time2024-02-11 18:40:38
maintainer
docs_urlNone
author
requires_python>=3.8
license
keywords wagtail django media
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # [wagtailmedia](https://pypi.org/project/wagtailmedia/)

[![PyPI](https://img.shields.io/pypi/v/wagtailmedia.svg)](https://pypi.org/project/wagtailmedia/)
[![PyPI downloads](https://img.shields.io/pypi/dm/wagtailmedia.svg)](https://pypi.org/project/wagtailmedia/)
[![Build Status](https://github.com/torchbox/wagtailmedia/workflows/CI/badge.svg)](https://github.com/torchbox/wagtailmedia/actions)
[![Coverage](https://codecov.io/github/torchbox/wagtailmedia/coverage.svg?branch=master)](https://codecov.io/github/torchbox/wagtailmedia?branch=master)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/torchbox/wagtailmedia/main.svg)](https://results.pre-commit.ci/latest/github/torchbox/wagtailmedia/main)

A module for Wagtail that provides functionality similar to `wagtail.documents` module,
but for audio and video files.

## Install

Install using pip:

```sh
pip install wagtailmedia
```

`wagtailmedia` is compatible with Wagtail 4.1 and above. Check out older releases for compatibility with older versions of Wagtail.

### Settings

In your settings file, add `wagtailmedia` to `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    # ...
    "wagtailmedia",
    # ...
]
```

All wagtailmedia settings are defined in a single `WAGTAILMEDIA` dictionary in your settings file. The
defaults are:

```python
# settings.py

WAGTAILMEDIA = {
    "MEDIA_MODEL": "wagtailmedia.Media",  # string, dotted-notation.
    "MEDIA_FORM_BASE": "",  # string, dotted-notation. Defaults to an empty string
    "AUDIO_EXTENSIONS": [
        "aac",
        "aiff",
        "flac",
        "m4a",
        "m4b",
        "mp3",
        "ogg",
        "wav",
    ],  # list of extensions
    "VIDEO_EXTENSIONS": [
        "avi",
        "h264",
        "m4v",
        "mkv",
        "mov",
        "mp4",
        "mpeg",
        "mpg",
        "ogv",
        "webm",
    ],  # list of extensions
}
```

### URL configuration

Your project needs to be set up to serve user-uploaded files from `MEDIA_ROOT`.
Your Django project may already have this in place, but if not, add the following snippet to `urls.py`:

```python
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

Note that this only works in development mode (`DEBUG = True`);
in production, you will need to configure your web server to serve files from `MEDIA_ROOT`.
For further details, see the Django documentation: [Serving files uploaded by a user during development](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-files-uploaded-by-a-user-during-development)
and [Deploying static files](https://docs.djangoproject.com/en/stable/howto/static-files/deployment/).

With this configuration in place, you are ready to run `./manage.py migrate` to create the database tables used by `wagtailmedia`.

`wagtailmedia` loads additional assets for the chooser panel interface.
Run `./manage.py collectstatic` after the migrations step to collect all the required assets.

### Custom `Media` model

The `Media` model can be customised. To do this, you need
to add a new model to your project that inherits from `wagtailmedia.models.AbstractMedia`.

Then set the `MEDIA_MODEL` attribute in the `WAGTAILMEDIA` settings dictionary to point to it:

```python
# settings.py
WAGTAILMEDIA = {
    "MEDIA_MODEL": "my_app.CustomMedia",
    # ...
}
```

You can customize the model form used with your `Media` model using the `MEDIA_FORM_BASE` setting.
It should be the dotted path to the form and will be used as the base form passed to `modelform_factory()` when constructing the media form.

```python
# settings.py

WAGTAILMEDIA = {
    "MEDIA_FORM_BASE": "my_app.forms.CustomMediaForm",
    # ...
}
```

### Hooks

#### `construct_media_chooser_queryset`

Called when rendering the media chooser view, to allow the media listing QuerySet to be customised.
The callable passed into the hook will receive the current media QuerySet and the request object,
and must return a Media QuerySet (either the original one, or a new one).

```python
from wagtail import hooks


@hooks.register("construct_media_chooser_queryset")
def show_my_uploaded_media_only(media, request):
    # Only show uploaded media
    media = media.filter(uploaded_by_user=request.user)

    return media
```

## How to use

### As a regular Django field

You can use `Media` as a regular Django field. Here’s an example:

```python
from django.db import models

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

from wagtailmedia.edit_handlers import MediaChooserPanel


class BlogPageWithMedia(Page):
    author = models.CharField(max_length=255)
    date = models.DateField("Post date")
    body = RichTextField(blank=False)
    featured_media = models.ForeignKey(
        "wagtailmedia.Media",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    content_panels = Page.content_panels + [
        FieldPanel("author"),
        FieldPanel("date"),
        FieldPanel("body"),
        MediaChooserPanel("featured_media"),
    ]
```

The `MediaChooserPanel` accepts the `media_type` keyword argument (kwarg) to limit the types of media that can be chosen or uploaded.
At the moment only "audio" (`MediaChooserPanel(media_type="audio")`) and "video" (`MediaChooserPanel(media_type="audio")`) are supported,
and any other type will make the chooser behave as if it did not get any kwarg.

#### Name clash with Wagtail

Do not name the field `media`. When rendering the admin UI, Wagtail uses a `media` property for its fields’ CSS & JS assets loading.
Using `media` as a field name breaks the admin UI ([#54](https://github.com/torchbox/wagtailmedia/issues/54)).

### In StreamField

You can use `Media` in StreamField. To do this, you need
to add a new block class that inherits from `wagtailmedia.blocks.AbstractMediaChooserBlock`
and implement your own `render_basic` method.

Here is an example:

```python
from django.db import models
from django.forms.utils import flatatt
from django.utils.html import format_html, format_html_join

from wagtail import blocks
from wagtail.admin.panels import FieldPanel
from wagtail.fields import StreamField
from wagtail.models import Page

from wagtailmedia.blocks import AbstractMediaChooserBlock


class TestMediaBlock(AbstractMediaChooserBlock):
    def render_basic(self, value, context=None):
        if not value:
            return ""

        if value.type == "video":
            player_code = """
            <div>
                <video width="{1}" height="{2}" controls>
                    {0}
                    Your browser does not support the video tag.
                </video>
            </div>
            """
        else:
            player_code = """
            <div>
                <audio controls>
                    {0}
                    Your browser does not support the audio element.
                </audio>
            </div>
            """

        return format_html(
            player_code,
            format_html_join(
                "\n", "<source{0}>", [[flatatt(s)] for s in value.sources]
            ),
            value.width,
            value.height,
        )


class BlogPage(Page):
    author = models.CharField(max_length=255)
    date = models.DateField("Post date")
    body = StreamField(
        [
            ("heading", blocks.CharBlock(classname="title", icon="title")),
            ("paragraph", blocks.RichTextBlock(icon="pilcrow")),
            ("media", TestMediaBlock(icon="media")),
        ]
    )

    content_panels = Page.content_panels + [
        FieldPanel("author"),
        FieldPanel("date"),
        FieldPanel("body"),
    ]
```

You can also use audio or video-specific choosers:

```python
# ...
from wagtail.models import Page
from wagtail.fields import StreamField
from wagtailmedia.blocks import AudioChooserBlock, VideoChooserBlock


class BlogPage(Page):
    # ...

    body = StreamField(
        [
            # ... other block definitions
            ("audio", AudioChooserBlock()),
            ("video", VideoChooserBlock()),
        ]
    )
```

### API

To expose media items in the API, you can follow the [Wagtail documentation guide](https://docs.wagtail.org/en/stable/advanced_topics/api/v2/configuration.html#api-v2-configuration)
for API configuration with wagtailmedia specifics:

```python
# api.py
from wagtail.api.v2.router import WagtailAPIRouter
from wagtailmedia.api.views import MediaAPIViewSet


# Register the router
api_router = WagtailAPIRouter("wagtailapi")
# add any other enpoints you need, plus the wagtailmedia one
api_router.register_endpoint("media", MediaAPIViewSet)
```

## Translations

wagtailmedia has translations in French and Chinese. More translations welcome!

## Contributing

All contributions are welcome!

### Install

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

```sh
git clone git@github.com:torchbox/wagtailmedia.git
cd wagtailmedia
```

With your preferred virtualenv activated, install testing dependencies:

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

### pre-commit

Note that this project uses [pre-commit](https://github.com/pre-commit/pre-commit). To set up locally:

```shell
# if you don't have it yet, globally
$ pip install pre-commit
# go to the project directory
$ cd wagtailmedia
# 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

Now you can run tests as shown below:

```sh
tox
```

or, you can run them for a specific environment `tox -e py310-dj41-wagtail41` or specific test
`tox -e py310-dj41-wagtail41 -- tests.test_views.TestMediaChooserUploadView`

To run the test app interactively, use `tox -e interactive`, visit `http://127.0.0.1:8020/admin/` and log in with `admin`/`changeme`.


            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "wagtailmedia",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "Dan Braghis <dan.braghis@torchbox.com>",
    "keywords": "Wagtail,Django,media",
    "author": "",
    "author_email": "Mikalai Radchuk  <hello@torchbox.com>",
    "download_url": "https://files.pythonhosted.org/packages/cd/76/c977b19ef962c7ae11258451b1b07f13bd9025de85476a2a7ea06336f9fa/wagtailmedia-0.15.1.tar.gz",
    "platform": null,
    "description": "# [wagtailmedia](https://pypi.org/project/wagtailmedia/)\n\n[![PyPI](https://img.shields.io/pypi/v/wagtailmedia.svg)](https://pypi.org/project/wagtailmedia/)\n[![PyPI downloads](https://img.shields.io/pypi/dm/wagtailmedia.svg)](https://pypi.org/project/wagtailmedia/)\n[![Build Status](https://github.com/torchbox/wagtailmedia/workflows/CI/badge.svg)](https://github.com/torchbox/wagtailmedia/actions)\n[![Coverage](https://codecov.io/github/torchbox/wagtailmedia/coverage.svg?branch=master)](https://codecov.io/github/torchbox/wagtailmedia?branch=master)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/torchbox/wagtailmedia/main.svg)](https://results.pre-commit.ci/latest/github/torchbox/wagtailmedia/main)\n\nA module for Wagtail that provides functionality similar to `wagtail.documents` module,\nbut for audio and video files.\n\n## Install\n\nInstall using pip:\n\n```sh\npip install wagtailmedia\n```\n\n`wagtailmedia` is compatible with Wagtail 4.1 and above. Check out older releases for compatibility with older versions of Wagtail.\n\n### Settings\n\nIn your settings file, add `wagtailmedia` to `INSTALLED_APPS`:\n\n```python\nINSTALLED_APPS = [\n    # ...\n    \"wagtailmedia\",\n    # ...\n]\n```\n\nAll wagtailmedia settings are defined in a single `WAGTAILMEDIA` dictionary in your settings file. The\ndefaults are:\n\n```python\n# settings.py\n\nWAGTAILMEDIA = {\n    \"MEDIA_MODEL\": \"wagtailmedia.Media\",  # string, dotted-notation.\n    \"MEDIA_FORM_BASE\": \"\",  # string, dotted-notation. Defaults to an empty string\n    \"AUDIO_EXTENSIONS\": [\n        \"aac\",\n        \"aiff\",\n        \"flac\",\n        \"m4a\",\n        \"m4b\",\n        \"mp3\",\n        \"ogg\",\n        \"wav\",\n    ],  # list of extensions\n    \"VIDEO_EXTENSIONS\": [\n        \"avi\",\n        \"h264\",\n        \"m4v\",\n        \"mkv\",\n        \"mov\",\n        \"mp4\",\n        \"mpeg\",\n        \"mpg\",\n        \"ogv\",\n        \"webm\",\n    ],  # list of extensions\n}\n```\n\n### URL configuration\n\nYour project needs to be set up to serve user-uploaded files from `MEDIA_ROOT`.\nYour Django project may already have this in place, but if not, add the following snippet to `urls.py`:\n\n```python\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n    # ... the rest of your URLconf goes here ...\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n```\n\nNote that this only works in development mode (`DEBUG = True`);\nin production, you will need to configure your web server to serve files from `MEDIA_ROOT`.\nFor further details, see the Django documentation: [Serving files uploaded by a user during development](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-files-uploaded-by-a-user-during-development)\nand [Deploying static files](https://docs.djangoproject.com/en/stable/howto/static-files/deployment/).\n\nWith this configuration in place, you are ready to run `./manage.py migrate` to create the database tables used by `wagtailmedia`.\n\n`wagtailmedia` loads additional assets for the chooser panel interface.\nRun `./manage.py collectstatic` after the migrations step to collect all the required assets.\n\n### Custom `Media` model\n\nThe `Media` model can be customised. To do this, you need\nto add a new model to your project that inherits from `wagtailmedia.models.AbstractMedia`.\n\nThen set the `MEDIA_MODEL` attribute in the `WAGTAILMEDIA` settings dictionary to point to it:\n\n```python\n# settings.py\nWAGTAILMEDIA = {\n    \"MEDIA_MODEL\": \"my_app.CustomMedia\",\n    # ...\n}\n```\n\nYou can customize the model form used with your `Media` model using the `MEDIA_FORM_BASE` setting.\nIt should be the dotted path to the form and will be used as the base form passed to `modelform_factory()` when constructing the media form.\n\n```python\n# settings.py\n\nWAGTAILMEDIA = {\n    \"MEDIA_FORM_BASE\": \"my_app.forms.CustomMediaForm\",\n    # ...\n}\n```\n\n### Hooks\n\n#### `construct_media_chooser_queryset`\n\nCalled when rendering the media chooser view, to allow the media listing QuerySet to be customised.\nThe callable passed into the hook will receive the current media QuerySet and the request object,\nand must return a Media QuerySet (either the original one, or a new one).\n\n```python\nfrom wagtail import hooks\n\n\n@hooks.register(\"construct_media_chooser_queryset\")\ndef show_my_uploaded_media_only(media, request):\n    # Only show uploaded media\n    media = media.filter(uploaded_by_user=request.user)\n\n    return media\n```\n\n## How to use\n\n### As a regular Django field\n\nYou can use `Media` as a regular Django field. Here\u2019s an example:\n\n```python\nfrom django.db import models\n\nfrom wagtail.fields import RichTextField\nfrom wagtail.models import Page\nfrom wagtail.admin.panels import FieldPanel\n\nfrom wagtailmedia.edit_handlers import MediaChooserPanel\n\n\nclass BlogPageWithMedia(Page):\n    author = models.CharField(max_length=255)\n    date = models.DateField(\"Post date\")\n    body = RichTextField(blank=False)\n    featured_media = models.ForeignKey(\n        \"wagtailmedia.Media\",\n        null=True,\n        blank=True,\n        on_delete=models.SET_NULL,\n        related_name=\"+\",\n    )\n\n    content_panels = Page.content_panels + [\n        FieldPanel(\"author\"),\n        FieldPanel(\"date\"),\n        FieldPanel(\"body\"),\n        MediaChooserPanel(\"featured_media\"),\n    ]\n```\n\nThe `MediaChooserPanel` accepts the `media_type` keyword argument (kwarg) to limit the types of media that can be chosen or uploaded.\nAt the moment only \"audio\" (`MediaChooserPanel(media_type=\"audio\")`) and \"video\" (`MediaChooserPanel(media_type=\"audio\")`) are supported,\nand any other type will make the chooser behave as if it did not get any kwarg.\n\n#### Name clash with Wagtail\n\nDo not name the field `media`. When rendering the admin UI, Wagtail uses a `media` property for its fields\u2019 CSS & JS assets loading.\nUsing `media` as a field name breaks the admin UI ([#54](https://github.com/torchbox/wagtailmedia/issues/54)).\n\n### In StreamField\n\nYou can use `Media` in StreamField. To do this, you need\nto add a new block class that inherits from `wagtailmedia.blocks.AbstractMediaChooserBlock`\nand implement your own `render_basic` method.\n\nHere is an example:\n\n```python\nfrom django.db import models\nfrom django.forms.utils import flatatt\nfrom django.utils.html import format_html, format_html_join\n\nfrom wagtail import blocks\nfrom wagtail.admin.panels import FieldPanel\nfrom wagtail.fields import StreamField\nfrom wagtail.models import Page\n\nfrom wagtailmedia.blocks import AbstractMediaChooserBlock\n\n\nclass TestMediaBlock(AbstractMediaChooserBlock):\n    def render_basic(self, value, context=None):\n        if not value:\n            return \"\"\n\n        if value.type == \"video\":\n            player_code = \"\"\"\n            <div>\n                <video width=\"{1}\" height=\"{2}\" controls>\n                    {0}\n                    Your browser does not support the video tag.\n                </video>\n            </div>\n            \"\"\"\n        else:\n            player_code = \"\"\"\n            <div>\n                <audio controls>\n                    {0}\n                    Your browser does not support the audio element.\n                </audio>\n            </div>\n            \"\"\"\n\n        return format_html(\n            player_code,\n            format_html_join(\n                \"\\n\", \"<source{0}>\", [[flatatt(s)] for s in value.sources]\n            ),\n            value.width,\n            value.height,\n        )\n\n\nclass BlogPage(Page):\n    author = models.CharField(max_length=255)\n    date = models.DateField(\"Post date\")\n    body = StreamField(\n        [\n            (\"heading\", blocks.CharBlock(classname=\"title\", icon=\"title\")),\n            (\"paragraph\", blocks.RichTextBlock(icon=\"pilcrow\")),\n            (\"media\", TestMediaBlock(icon=\"media\")),\n        ]\n    )\n\n    content_panels = Page.content_panels + [\n        FieldPanel(\"author\"),\n        FieldPanel(\"date\"),\n        FieldPanel(\"body\"),\n    ]\n```\n\nYou can also use audio or video-specific choosers:\n\n```python\n# ...\nfrom wagtail.models import Page\nfrom wagtail.fields import StreamField\nfrom wagtailmedia.blocks import AudioChooserBlock, VideoChooserBlock\n\n\nclass BlogPage(Page):\n    # ...\n\n    body = StreamField(\n        [\n            # ... other block definitions\n            (\"audio\", AudioChooserBlock()),\n            (\"video\", VideoChooserBlock()),\n        ]\n    )\n```\n\n### API\n\nTo expose media items in the API, you can follow the [Wagtail documentation guide](https://docs.wagtail.org/en/stable/advanced_topics/api/v2/configuration.html#api-v2-configuration)\nfor API configuration with wagtailmedia specifics:\n\n```python\n# api.py\nfrom wagtail.api.v2.router import WagtailAPIRouter\nfrom wagtailmedia.api.views import MediaAPIViewSet\n\n\n# Register the router\napi_router = WagtailAPIRouter(\"wagtailapi\")\n# add any other enpoints you need, plus the wagtailmedia one\napi_router.register_endpoint(\"media\", MediaAPIViewSet)\n```\n\n## Translations\n\nwagtailmedia has translations in French and Chinese. More translations welcome!\n\n## Contributing\n\nAll contributions are welcome!\n\n### Install\n\nTo make changes to this project, first clone this repository:\n\n```sh\ngit clone git@github.com:torchbox/wagtailmedia.git\ncd wagtailmedia\n```\n\nWith your preferred virtualenv activated, install testing dependencies:\n\n```sh\npip install -e '.[testing]' -U\n```\n\n### pre-commit\n\nNote that this project uses [pre-commit](https://github.com/pre-commit/pre-commit). To set up locally:\n\n```shell\n# if you don't have it yet, globally\n$ pip install pre-commit\n# go to the project directory\n$ cd wagtailmedia\n# initialize pre-commit\n$ pre-commit install\n\n# Optional, run all checks once for this, then the checks will run only on the changed files\n$ pre-commit run --all-files\n```\n\n### How to run tests\n\nNow you can run tests as shown below:\n\n```sh\ntox\n```\n\nor, you can run them for a specific environment `tox -e py310-dj41-wagtail41` or specific test\n`tox -e py310-dj41-wagtail41 -- tests.test_views.TestMediaChooserUploadView`\n\nTo run the test app interactively, use `tox -e interactive`, visit `http://127.0.0.1:8020/admin/` and log in with `admin`/`changeme`.\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "A Wagtail module for audio and video files.",
    "version": "0.15.1",
    "project_urls": {
        "Changelog": "https://github.com/torchbox/wagtailmedia/blob/main/CHANGELOG.md",
        "Issues": "https://github.com/torchbox/wagtailmedia/issues",
        "Repository": "https://github.com/torchbox/wagtailmedia"
    },
    "split_keywords": [
        "wagtail",
        "django",
        "media"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0e9aa5f19b268cca27776820e73c850972bce91dc9fd7262066660f70b4bc94f",
                "md5": "3cdcd2742449ca824b1d98481327bcaa",
                "sha256": "4aff072de282ea3c0e5df8525e620e27752f8e0a0a223b48f89d89a5c0f6b335"
            },
            "downloads": -1,
            "filename": "wagtailmedia-0.15.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3cdcd2742449ca824b1d98481327bcaa",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 82598,
            "upload_time": "2024-02-11T18:40:37",
            "upload_time_iso_8601": "2024-02-11T18:40:37.072094Z",
            "url": "https://files.pythonhosted.org/packages/0e/9a/a5f19b268cca27776820e73c850972bce91dc9fd7262066660f70b4bc94f/wagtailmedia-0.15.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cd76c977b19ef962c7ae11258451b1b07f13bd9025de85476a2a7ea06336f9fa",
                "md5": "46ceaf359bda8b30bc9b3726e417971c",
                "sha256": "1d16610f3b0f4b31012135ed4069c16da23fe9d69420969a5030d61e559b2144"
            },
            "downloads": -1,
            "filename": "wagtailmedia-0.15.1.tar.gz",
            "has_sig": false,
            "md5_digest": "46ceaf359bda8b30bc9b3726e417971c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 51835,
            "upload_time": "2024-02-11T18:40:38",
            "upload_time_iso_8601": "2024-02-11T18:40:38.596891Z",
            "url": "https://files.pythonhosted.org/packages/cd/76/c977b19ef962c7ae11258451b1b07f13bd9025de85476a2a7ea06336f9fa/wagtailmedia-0.15.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-11 18:40:38",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "torchbox",
    "github_project": "wagtailmedia",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "tox": true,
    "lcname": "wagtailmedia"
}
        
Elapsed time: 0.21929s