Reputation: 197
I have a Django app that uses different static files such as images, css files, and js files. That being said, the documentation https://docs.djangoproject.com/en/2.2/howto/static-files/ shows two different ways to serve static files, and I've also seen developers follow both methods.
I'm currently doing it like this:
#settings.py
STATIC_URL = '/static/'
# whatever.html
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
With all my images inside the same folder as my main.css file.
But I've also seen developers following the second method of the documentation:
#settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
#urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When using the second method, they'll have a different folder called media that is located at the same level as all main apps. Supposedly I'd leave my images in there.
I'm wondering if it's okay to follow the first method (using {% load static %}) which is what I'm doing, and what the difference between the two methods is.
Thank you!
Upvotes: 1
Views: 74
Reputation: 13057
Actually Django
doesn't consider both as static files.
Static Files Images
<img src="{% static "my_app/example.jpg" %}" alt="My image">
These are the application media files and are supposed to be used in the application wide scope. They are particularly meant to be used in css, js etc.
Media Files Images
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
These media files are for user-uploaded content. It particularly deals with the request response cycle.
Note: Django disentangles user uploaded media from application media, thus making deployment, backups, and version control easier.
Upvotes: 1