pythondjangodjango-templatesdjango-staticfilesdjango-static

Serving static files from the project directory in Django


I have the following project structure:

myproject
    - myapp
    - manage.py
    - myproject
          - settings.py
          - urls.py
          ...
    - static
    - templates

I want to serve all my static files from within this static folder. In my settings.py, I have the following:

STATIC_URL = '/static/'

However, in one of my templates, when I call static files using the following...

{% load static %}
...
<link href="{% static 'css/styles.css' %}" rel="stylesheet" />

...nothing gets loaded.

However, if I add the css file within myapp/static/css/styles.css, then everything works properly. How can I serve static files from my project root folder? Thanks for any help.


Solution

  • First Step: Your project structure(folder directory) seems to be ok.

    myproject
    - myapp
    - manage.py
    - myproject
          - settings.py
          - urls.py
          ...
    - static
    - templates
    

    Second: Need to define the STATIC_URL = '/static/' in settings.py file.

    Third: Need to load the static in the template file and use the relative path.

    {% load static %}
    ...
    <link href="{% static 'css/styles.css' %}" rel="stylesheet" />
    

    Add this settings.py file.

    # Add static file directory
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
    

    Installed Apps listing in settings.py is supposed to exist in the django.contrib.staticfiles in the list. if not then make sure its in the list.