简体   繁体   中英

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' %}?

How to setup it?

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 .

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM