• Stars
    star
    231
  • Rank 172,392 (Top 4 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 8 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Wagtail module for managing video and audio files within the admin

wagtailmedia

PyPI PyPI downloads Build Status Coverage pre-commit.ci status

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

Install

Install using pip:

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:

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

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

# 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:

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 and Deploying static files.

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:

# 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.

# 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).

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:

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).

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:

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:

# ...
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 for API configuration with wagtailmedia specifics:

# 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:

git clone [email protected]:torchbox/wagtailmedia.git
cd wagtailmedia

With your preferred virtualenv 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, 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:

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.

More Repositories

1

django-recaptcha

New maintainers 🚧 --- Django reCAPTCHA form field/widget integration app.
Python
929
star
2

django-pattern-library

UI pattern libraries for Django templates
Python
359
star
3

django-libsass

A django-compressor filter to compile SASS files using libsass
Python
265
star
4

vagrant-django-template

Skeleton project for a Django app running under Vagrant
Python
240
star
5

wagtail-markdown

Markdown support for Wagtail
Python
191
star
6

wagtail-grapple

A Wagtail app that makes building GraphQL endpoints a breeze!
Python
152
star
7

wagtail-torchbox

Wagtail build of Torchbox.com
Python
124
star
8

wagtail-headless-preview

Previews for headless Wagtail setups
Python
116
star
9

wagtail-experiments

A/B testing for Wagtail
Python
105
star
10

vagrant-django-base

Vagrant configuration for a base box for Django development
Shell
90
star
11

storybook-django

Develop Django UI components in isolation, with Storybook
JavaScript
83
star
12

cookiecutter-wagtail

Python
54
star
13

k8s-hostpath-provisioner

Network storage provisioner for Kubernetes
Go
52
star
14

kdtool

Kubernetes deployment utility
Python
45
star
15

kube-ldap-authn

Kubernetes LDAP authentication service
Python
42
star
16

wagtail-wordpress-import

A package for Wagtail CMS to import WordPress blog content from an XML file into Wagtail
Python
41
star
17

wagtail-storages

Use AWS S3 with private documents in Wagtail
Python
40
star
18

design-in-browser-bootstrap

An aid to quickly starting Design In the Browser
JavaScript
34
star
19

wagtail-import-export

UNMAINTAINED. Try wagtail-transfer, the evolution of this package: https://github.com/wagtail/wagtail-transfer/
Python
32
star
20

wagtail-content-import

A module for importing page content into Wagtail from third-party sources. Docs:
Python
32
star
21

rustface-py

Python library for detecting faces in images.
Rust
31
star
22

wagtailquickcreate

Wagtail Quick Create offers shortcut links to create objects from models specified in your settings file.
Python
25
star
23

wagtailguide

An app for adding a CMS guide to your Wagtail CMS
Python
23
star
24

k8s-ts-ingress

Kubernetes Ingress controller as a Traffic Server plugin
C
22
star
25

wagtailsurveys

Python
21
star
26

vagrant-thumbor-base

Vagrant box providing a thumbor service over HTTP
Shell
20
star
27

wagtail-footnotes

Python
19
star
28

wagtail-template

A Django template for starting new Wagtail projects with Vagrant. NO LONGER MAINTANED
Python
19
star
29

wagtail-ab-testing

A/B testing for Wagtail
Python
17
star
30

buckup

Creating S3 buckets for your site with ease.
Python
16
star
31

torchbox-frontend

JavaScript
16
star
32

wagtail-appengine-demo

The simplest possible Wagtail site on Google Cloud
CSS
15
star
33

django-basic-auth-ip-whitelist

Hide your Django site behind basic authentication with IP whitelisting support
Python
14
star
34

verdant-rca

Python
13
star
35

docker-php

Docker PHP Images based on official PHP
Shell
12
star
36

longform

A plugin for longform content in Wagtail
CSS
12
star
37

wagtail-purge

A simple Wagtail admin UI for removing individual pages from your CDN's cache
Python
10
star
38

wagtail-webstories

AMP web story support for Wagtail
Python
9
star
39

cloudflare-recipes

Cloudflare service worker recipes
JavaScript
7
star
40

rca-wagtail-2019

Python
7
star
41

trafficserver-ingress-controller

Apache Traffic Server ingress controller for Kubernetes
Perl
7
star
42

tbxforms

A Torchbox-flavoured template pack for django-crispy-forms, adapted from crispy-forms-gds.
HTML
6
star
43

stylelint-config-torchbox

Shareable stylelint config for CSS and SCSS, following Torchbox’s code style.
JavaScript
6
star
44

wagtailapi

A module for adding a read only, JSON based web API to your Wagtail site (NO LONGER MAINTAINED! Use Wagtails contrib.wagtailapi module instead)
Python
6
star
45

webstories

Parser for AMP web stories
Python
6
star
46

wagtail-makeup

Wagtail plugin to replace all your broken local images with unsplash ones
Python
6
star
47

samaritans-patterns

HTML
5
star
48

wagtail-bookmarklet

Gives Wagtail editors an 'edit this page' bookmarklet, for scenarios where the user bar isn't available
Python
5
star
49

django-registration

Tweaked Django >=1.6-compatible version of django-registration
Python
5
star
50

careers

Torchbox careers site
TypeScript
4
star
51

ample

Cross-browser audio playback library, with HTML5 and Flash backends
JavaScript
4
star
52

nhs-organisations

Python
3
star
53

wagtail-jotform

A plugin for using jotforms in wagtail
Python
3
star
54

wagtail-bynder

Wagtail + Bynder Digital Asset Management System integration
Python
3
star
55

wagtailapidemo

Wagtaildemo with API enabled
Python
3
star
56

eslint-config-torchbox

Shareable ESLint config following Torchbox’s code style
JavaScript
3
star
57

wagtail-mongodb

Python
3
star
58

dit_directory_cms_poc

Proof-of-concepts for potential improvements to uktrade/directory-cms
Python
2
star
59

christmas-video-2017

CSS
2
star
60

wagtail-related

Python
2
star
61

resourcespace_plugin-api_markasused

API plugin for resourcespace that updates a resourcespace entry
PHP
2
star
62

wagtail-azure-cdn

Use Azure CDN with Wagtail CMS.
Python
2
star
63

heroku-cloudflare-app-domain

Create branded herokuapp.com domains through Cloudflare
Python
2
star
64

demo.wagtail.io

Configuration for demo.wagtail.io
Python
2
star
65

christmaschorus

the 2011 musical christmas card
JavaScript
2
star
66

ngxpurged

nginx cache purge daemon
Python
2
star
67

django-tagging

Fork via PyPI v0.3.4 to maintain Django compatibility. Unmaintained for Django >= 1.10
Python
2
star
68

torchbox.com

Torchbox website 2024 incarnation
Python
2
star
69

resourcespace_plugin-api_resource

API plugin for resourcespace that fetches a resource metadata or a resource file in stream
PHP
2
star
70

docker-rsync

Trivial Docker image containing Alpine Linux with rsync installed
Makefile
1
star
71

heroku-restarter

Restarts Heroku applications based on timeout alerts in Papertrail
Python
1
star
72

django-piston

Fork of the popular REST API mini-framework
Python
1
star
73

kube-registry-proxy

Shell
1
star
74

tate-cms

Tate CMS project’s sprint notes
1
star
75

docker-trafficserver

1
star
76

healtheintent-api-python

Python
1
star
77

raxtool

Rackspace Cloud management tool
Python
1
star
78

ceph-rbd-provisioner

1
star
79

django-importo

A developer-friendly framework for importing data into Django apps
Python
1
star
80

wagtail_picture_proposal

Code snippets for an experimental picture tag for Wagtail. Not intended for reuse
Python
1
star
81

nlbq

Natural language interface to BigQuery
Python
1
star
82

nuffield-nhs-timeline

Nuffield NHS Timeline
HTML
1
star