Luca
Luca

Reputation: 10996

django static file loading adds a non-existent directory to the file path

I have a Django project which has the following settings for loading static files:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'proj.apps.ProjConfig',
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "images/"),
]

LOGIN_REDIRECT_URL = 'login'

My urls.py is defined as:

from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.contrib.auth import views as auth_views
from proj import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name='index'),
    url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
    url(r'^logout/$', auth_views.logout, name='logout'),
] + staticfiles_urlpatterns()

I have a file called logo.png which is copied to the satic directory when I run python manage.py collectstatic as expected.

My template for login (login.html) attempts to load this file as follows:

{% extends 'base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
    {% load static %}
    <img src="{% static "logo.png" %}" alt="My image"/>

  <h2>Login</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
  </form>
{% endblock %}

Now the image is not loaded and the error comes with:

Not Found: /login/logo.png

I am not sure why it prepends the /login/ directory to the path and I have been trying to figure this out for hours without luck!

I am in development mode (Debug=True) on a Windows machine. The path for the logo.png file is proj_base_directory\\static\logo.png

Upvotes: 0

Views: 149

Answers (1)

Gil Guilherme
Gil Guilherme

Reputation: 252

Try to use the solution to serve static files during development:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ....
] 

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

PROBLEM SOLVED:

Your STATIC_URL should be STATIC_URL = '/static/' in your settings.py

Upvotes: 1

Related Questions