Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Bapi Roy
Bapi Roy
14,237 Points

MEDIA_URL vs STATIC_URL in django

Please explain the difference between STATIC_URL and MEDIA_URL.

How to use an image that is under MEDIA_ROOT directory?

1 Answer

Marilyn Magnusen
Marilyn Magnusen
14,084 Points

Hi Bapi,

MEDIA_URL should be used for user generated content STATIC_URL should be used images that you yourself add to your website, for example your profile picture on an 'about us' page

Your settings.py file should have both MEDIA_URL and STATIC_URL defined like this:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# Marilyn setting path for user generated contenttypes
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

The above is telling Django where to look and giving it the path to your files for images served on your webpage.

If you then want to add your profile picture to a webpage:

1.create a folder named static within your app

2.create a subfolder named 'images'

3.upload your image to the 'images' subfolder

To use that image on in your html code, it would look like this:

{% load staticfiles %}

<img src="{{STATIC_URL}}static/images/cv.png" alt="marilyns image" id="homepage-cv"/>

Feel free to reach out if you need help with user uploaded images :)

Hope this helps!

Bapi Roy
Bapi Roy
14,237 Points

Thank you for your response.