Sebastian Olsen
Sebastian Olsen

Reputation: 10878

Static folder not being loaded

I want to insert the avatar of the currently logged in user into the header, but I can't get the files to load. I've checked the installed apps, the directory from where it should look but to no avail.

Here's my template:

{% load static from staticfiles %}

<header>
    <div id="header_title">App name goes here</div>
    <div id="header_nav">
        <nav>
            {% if user.is_authenticated %}
            <a href="home">Home</a>
            <a href="feed">Feed</a>
            <a href="me">
               {% load staticfiles %}
                <img src="{% static 'user/'%}{{request.user}}/avatar.png" alt="">
            </a>
            <a href="notifications">N</a>
            <a href="settings">
                <div>S</div>
            </a>
            {% else %}
            <a href="login">Log in</a>
            <a href="register">Register</a>
            {% endif %}
        </nav>
    </div>
</header>

And my settings.py:

...

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tracks',
...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.core.context_processors.static',
                'django.core.context_processors.media',
            ],
        },
    },
]

...

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

STATIC_URL = '/static/'
AUTH_PROFILE_MODULE = 'tracks.UserProfile'

This does not show the image, instead it shows the "image not found" icon.

What is going on here? Why is it not loading the files and displaying them? Going to the url "/static/user/enitoni/avatar.png" gives me a 404 error.

Here's the rendered html if it helps:

<a href="me">
  <img src="/static/user/enitoni/avatar.png" alt="">
</a>

Upvotes: 1

Views: 54

Answers (1)

Madalosso
Madalosso

Reputation: 126

So... you define the STATIC_URL but didn`t define the STATIC_ROOT or STATIC_FILE_DIRS. The STATIC_URL will load static files present in a dir named 'static' that must be in your_app like:

my_app/static/my_app/myimage.jpg

and access through

<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>

If you need to load static files from outside your app, check the documentation: https://docs.djangoproject.com/en/1.9/howto/static-files/

Upvotes: 1

Related Questions