Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Custom inclusion template tag MEDIA_URL?

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?

like image 472
Hanpan Avatar asked Apr 21 '11 09:04

Hanpan


People also ask

How do I use custom template tags in Django?

Create a custom template tagUnder the application directory, create the templatetags package (it should contain the __init__.py file). For example, Django/DjangoApp/templatetags. In the templatetags package, create a . py file, for example my_custom_tags, and add some code to it to declare a custom tag.

What is inclusion tag in Django?

The Django developer can define the custom template tag and filter to the extent the template engine and the new template tag can be used using the {% custom_tag %}. The template tag that is used to display data by rendering another template is called the inclusion tag.

What is Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. template.html : <ul> {% for x in mymembers %} <li>{{ x. firstname }}</li> {% endfor %} </ul> Run Example »


1 Answers

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 }}" />
like image 176
bfschott Avatar answered Oct 11 '22 03:10

bfschott