darkhorse
darkhorse

Reputation: 8722

How to manage templates and static files for multiple apps in a Django project?

right now, I have 2 apps running in the same project. For the front-end, I am using Angular, so ideally, I would want to bring all these together in one place.

However, the way Django's templates and static files are handled is that these are placed within the app's folders.

What would be the right way to bring these together in one location? I don't need to have templates, and static folder inside each of my app's folders, since I am using a framework for my front end.

For example: I have this in my urls.py

url(r'^$', TemplateView.as_view(template_name='base.html')),

This works if I put a base.html file in either of the following:

So, what is the conventionally right way of doing things like this?

Upvotes: 3

Views: 2182

Answers (1)

Cadmus
Cadmus

Reputation: 665

Django Static Settings

You can resolve this issue with static settings, put all your static related files into a static folder with your needs like the example

project/static/app1/css/style.css
project/static/app2/css/style.css 

settings.py

import os
def root(folder):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',folder)

STATIC_ROOT = root('staticstorage')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
    root('static'),
)

urls.py

from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

make sure you have rum python manage.py collectstatic

in your template folder

base.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="/static/app1/js/jquery-1.10.1.min.js"></script>
    </head>
    <body>
        
    </body>
</html>

base2.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="/static/app2/js/jquery-1.10.1.min.js"></script>
    </head>
    <body>
        
    </body>
</html>


{% extends 'base1.html'%}
<h1>Hello world app1 </h1


{% extends 'base2.html'%}
<h1>Hello world app2 </h1>

Upvotes: 2

Related Questions