简体   繁体   English

如何管理 Django 项目中多个应用程序的模板和静态文件?

[英]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.现在,我在同一个项目中运行了 2 个应用程序。 For the front-end, I am using Angular, so ideally, I would want to bring all these together in one place.对于前端,我使用的是 Angular,所以理想情况下,我希望将所有这些放在一个地方。

However, the way Django's templates and static files are handled is that these are placed within the app's folders.但是,Django 的模板和静态文件的处理方式是将它们放置在应用程序的文件夹中。

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例如:我的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:如果我将 base.html 文件放在以下任一位置,这将起作用:

  • myapp1/templates/ myapp1/模板/
  • myapp2/templates/ myapp2/模板/

So, what is the conventionally right way of doing things like this?那么,做这种事情的传统正确方法是什么?

Django Static Settings Django 静态设置

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设置.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网址.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确保你有朗姆酒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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM