I am trying serve static files in my local development (on same server I serve my site). I have run ./manage.py collectstatic
with the following configs:
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
template.html
{% load static %}
<img src="{% static 'apis/icons/random-svgrepo-com.svg' %}" style="width: 50px;">
Now I have staticfiles folder in my BASE_DIR folder, but when I try to get an image, it doesn't appear to be working expected.
http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg
Please help. What I am doing wrong?
CodePudding user response:
First of all I think you have not configured your static files and media files. Try configuring it as follows. In your settings.py ensure to include STATICFILES_DIR, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT
in your settings.py
and then add the below lines below STATIC_URL = 'static/'
:
STATIC_URL = 'static/'
MEDIA_URL = 'media/'
STATICFILES_DIRS = [BASE_DIR / 'staticfiles']
STATIC_ROOT = BASE_DIR / 'staticfiles/'
MEDIA_ROOT = BASE_DIR / 'static/media'
By doing this you are telling django where to get your static files. now your have to add the link of the static files in your project urls.py
. you will add that as below.
from django.conf import settings
from django.conf.urls.static import
static
urlpatterns = [
.......
]
urlpatterns =static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
One last thing that I assumed you had done is creating static folder in your project root and inside that static folder create media folder where all the images you want to load are. Now run python manage.py
collectstatic