9

I have the following custom inclusion tag:

from django.template import Library
from django.db.models import Count

register = Library()

@register.inclusion_tag('projects/work_part.html', takes_context=True)
def project_list(context):
    return {'projects':context['projects']}

My settings look like this:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'context_processors.default_processors',
    )

I need to access MEDIA_URL within the work_path.html template but it seems the context processors are not applied to custom templates.

How do I access MEDIA_URL within my template tag? I saw this post: Access STATIC_URL from within a custom inclusion template tag but I am not using STATIC_URL, is there another set of tags I should be loading?

Community
  • 1
  • 1
Hanpan
  • 10,013
  • 25
  • 77
  • 115
  • As mentioned in the first answer to the thread you linked: Why don't you import MEDIA_URL in your template tag code and pass it to the template? – arie Apr 21 '11 at 09:24

3 Answers3

15

The get_media_prefix tag is in static for those of us that were looking to "load media"...

{% load static %}
...
<img class="img" src="{% get_media_prefix %}{{ obj.image }}" alt="{{ obj.name }}" />
bfschott
  • 311
  • 3
  • 8
5

You can do the same (as with STATIC_URL) using the tempatetag {% get_media_prefix %}

manji
  • 47,442
  • 5
  • 96
  • 103
  • Oh man do I feel stupid, I don't know why I didn't think to try that. Thanks! – Hanpan Apr 21 '11 at 09:28
  • 1
    When you get a `TemplateSyntaxError` because the tag doesn't exist, see user1653114's answer: http://stackoverflow.com/a/12307683/400691 – meshy Apr 22 '13 at 09:23
-1

Or you can just ignore those template tag and use MEDIA_URL variable right away. All of the variables from settings.py are accessible from the template HTML.

<img class="img" src="{{ MEDIA_URL }}{{ obj.image }}" alt="{{ obj.name }}" />
Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
  • that's exactly _NOT_ working for the questioner, hence the question in the first place. – nuts Aug 25 '19 at 10:03