Skip to content Skip to sidebar Skip to footer

Django Media Url Tag

Does django have media tag similar to static and url and how to setup it? {% static 'styles/boo.css' %} {% url 'some_app:some_name' %} Is this possible: {% media 'what here' %}?

Solution 1:

There is no media template tag.

Having set MEDIA_ROOT and MEDIA_URL you can use a media file in a template by referring to its url attribute.

For example:

classFoo(models.Model):
    image = models.ImageField(
        ...
    )

and then in your template:

<imgsrc="{{ foo_object.image.url }}">

Also, take a look at the docs about how to access media files.

Solution 2:

You need {% get_media_prefix %}.

The way to set it up is explained in the docs: you have to set the MEDIA_ROOT and the MEDIA_URL in your settings and add the MEDIA_URL to your urls.py.

Solution 3:

{% get_media_prefix %} and {{MEDIA_URL}} via context processor are both good alternatives for what you ask.

That being said, if what you really want to achieve is to render a link to an uploaded media file such as an image, there is a better way.

Model:

classCompany(models.Model):
    logo = models.ImageField()

    @propertydeflogo_url(self):
        if self.logo andhasattr(self.logo, 'url'):
            return self.logo.url

Template:

<imgsrc="{{company.logo_url}}"/>

The reason for the @property is that you want to avoid cases where the ImageField doesn't contain an image. Accessing company.logo.url directly in the template will cause an exception in such a case.

This is actually a long standing issue in Django: https://code.djangoproject.com/ticket/13327

Solution 4:

For media files I use django-imagekit Basic use:

from django.dbimport models
from imagekit.modelsimportProcessedImageFieldfrom imagekit.processorsimportResizeToFill

models.py

classPhoto(models.Model):
    owner = models.ForeignKey(Project, on_delete=models.CASCADE)
    photos = ProcessedImageField(upload_to='pagename/images',
                                       processors=[ResizeToFill(900, 600)],
                                       format='JPEG',
                                       options={'quality': 90})

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'imagekit',
]

.html

{% load imagekit %}

{% thumbnail '100x50' source_file %}

Read documentation - https://pypi.python.org/pypi/django-imagekit

Post a Comment for "Django Media Url Tag"