Django - Load static files from another app
Asked Answered
Z

3

8

In app1 I am trying to load static files from app2. I set no STATICFILES_FINDERS in project settings.py, which means, Django will use default AppDirectoriesFinder when it finds static subdirectory inside app directory.

Problem:

In template files of app1, I can generate urls of static files for app1 very easily. But if I want app1 template files to generate urls for static files of app2, links are not working. How can I in app1 generate static files of app2?

App1 template file:

{% load static %}
<img src="{% static "app1/example.jpg" %}"> <!-- ok -->
<img src="{% static "app2/example.jpg" %}"> <!-- link broken -->

HTML Output:

<img src="http://localhost:8000/static/app1/example.jpg">
<img src="http://localhost:8000/static/app2/example.jpg"> 
Zebrass answered 29/1, 2017 at 21:15 Comment(0)
Z
1

I found a solution. Please be aware, that directory in your project folder, which is named exactly same as your project folder is not an app. At first thought it is the initial app, that is automatically created by Django, but it isnt.

If you have two apps, and you want to load static files between them, code examples above works.

Zebrass answered 11/2, 2017 at 7:41 Comment(0)
S
8

I had the same problem. I handled it setting this var in settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app1/static/'),
    os.path.join(BASE_DIR, 'app2/static/'),
]

So, both dirs become avaliable in static template tag regardless from which app you're calling it.

I'm using django 2.1. Obs: 1 - Maybe this come set by default when you use the startapp command. Idk. 2 - BASE_DIR is the abs path to settings.py.

Shirelyshirey answered 22/8, 2018 at 12:16 Comment(0)
Z
1

I found a solution. Please be aware, that directory in your project folder, which is named exactly same as your project folder is not an app. At first thought it is the initial app, that is automatically created by Django, but it isnt.

If you have two apps, and you want to load static files between them, code examples above works.

Zebrass answered 11/2, 2017 at 7:41 Comment(0)
G
0

Just add this to your settings.py (from the Django documentation)

STATICFILES_DIRS = [
    BASE_DIR / "static",
    'var/www/static/',
]
Guadiana answered 8/1, 2021 at 6:38 Comment(1)
Can you link where in the docs this is mentioned? Thanks!Dziggetai

© 2022 - 2024 — McMap. All rights reserved.