[Django]-Django media url tag

37👍

You need {% get_media_prefix %}.

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

57👍

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:

class Foo(models.Model):
    image = models.ImageField(
        ...
    )

and then in your template:

<img src="{{ foo_object.image.url }}">

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

12👍

{% 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:

class Company(models.Model):
    logo = models.ImageField()

    @property
    def logo_url(self):
        if self.logo and hasattr(self.logo, 'url'):
            return self.logo.url

Template:

<img src="{{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

3👍

For media files I use django-imagekit
Basic use:

from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill

models.py

class Photo(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

Leave a comment