2

A rather simple question which I will elaborate on if needed in order to solve the problem.

I attempted to use a simple call to {{ MEDIA_URL }} in order to show an image on an About Us Django flatpage, but it seems the flatpage is ignoring the fact that it is a Django variable and simply taking {{MEDIA_URL}} as text?

I supplied: <img src="{{ MEDIA_URL }}images/static/Deb-and-Diana-About-Us.jpg" alt="Deb &amp; Diana Portrait" width="300" height="384" align="left"> but when the template is rendered it doesn't append the MEDIA_URL where it should, it just leaves the words {{ MEDIA_URL }}.

Am I missing an import or something? The default.html which governs the flatpage extends my usual template so I see no reason why this should fail, unless I don't understand what flatpages have access to?

karthikr
  • 97,368
  • 26
  • 197
  • 188
fildred13
  • 2,280
  • 8
  • 28
  • 52
  • possible duplicate of [Extending Django Flatpages to accept template tags](http://stackoverflow.com/questions/3066270/extending-django-flatpages-to-accept-template-tags) – Aamir Rind Jul 17 '13 at 01:43
  • @AamirAdnan This question has nothing to do with what you have marked as duplicate.. – karthikr Jul 17 '13 at 01:50
  • @karthikr how? What is difference between a MEDIA_URL and other template tags or context? – Aamir Rind Jul 17 '13 at 11:03
  • @AamirAdnan The question is, How to I enable `MEDIA_URL` in flatpages, not how do i make flatpages accept templatetags. There are many ways of doing that – karthikr Jul 17 '13 at 14:41

1 Answers1

6

You can access the MEDIA_URL in flat pages via a templatetag. Look at this snippet It searches for {{ MEDIA_URL }} and replaces it with that found in your settings.

from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def media_url(value):
    """Searches for {{ MEDIA_URL }} and replaces it with the MEDIA_URL from settings.py"""
    return value.replace('{{ MEDIA_URL }}', settings.MEDIA_URL)
media_url.is_safe = True

And the usage:

{% load media_url %}
{{ flatpage.content|media_url }}

To set up, drop the above code into a file called media_url.py in your templatetags directory in one of your INSTALLED_APPS, and add the filter to your flatpages template like so

karthikr
  • 97,368
  • 26
  • 197
  • 188