2

I'm trying to get a file that's in my media directory to appear on an HTML template. I'm using the "Tango with Django" book as a tutorial.

Here is my settings.py:

MEDIA_DIR = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

Here is views.py:

  def about(request):

    return render(request, 'rango/about.html', )

And my about.html template:

<!DOCTYPE html>
{%load staticfiles%}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About</title>
</head>
<body>
<h1>This is the about page</h1>
<img src="{{MEDIA_URL}} {{cat.jpg}}"
     alt="cats are funny"/>
<div>
    <a href="/rango/"> Index </a>
</div>
</body>
</html>

I know I must be missing something very obvious, but can't figure it out for the life of me!

2 Answers 2

3

The {{MEDIA_URL}} tag is deprecated. Use the {% get_media_prefix %} tag, instead.

<img src="{% get_media_prefix %}cat.jpg" alt="cats are funny"/>

From the documentation:

Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL.

When rendered, that src attribute will be equivalent to /media/cat.jpg. You may want to consider using STATIC_ROOT in your settings.py, instead, along with the {% static %} tag:

<img src="{% static 'cat.jpg' %}" alt="cats are funny"/>
Sign up to request clarification or add additional context in comments.

2 Comments

I replaced the media_url tag with the get_media_prefix tag, and now it's saying that I didn't register/load that tag. Sorry, I'm a complete newbie to this.
@MatthewSheinberg: I've added a link to the documentation for get_media_prefix. It looks like you'll need to replace {% load staticfiles %} with {% load static %}, as the former is also deprecated. You may also want to verify that the book you're reading is guiding you in the correct version of Django; the current version being 1.11. Here's a snippet from the docs that you can use to check your version.
0

I think the problems should be errors in format. Try the following two revisions: 1. in your render(), change "return render(request, 'rango/about.html', )" to "return render(request, 'rango/about.html') by deleting the last comma; 2. in your template file about.html, change .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.