django media url tag

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.


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.


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