python - Location of static files when creating a Django exe using pyinstaller - Stack Overflow

主要和国内流行文章的区别是,国内的都不太对

Now my top-level directory looked like this.

site
    app
        admin.py
        apps.py
        models.py
        views.py
    site
        asgi.py
        settings.py
        urls.py
        wsgi.py
    media
        media files
    staticfiles
        static files I want to serve (css, js, etc)

In my settings file I specified my static file settings like this...

STATIC_URL = '/staticfiles/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app\\static\\app')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Then in my urls.py file I included the staticfiles directory like this... (Note this is the urls.py file in the main site directory not in the app directory if you made one in there)

from django.contrib import admin
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static

urlpatterns = [
    path('', include('app.urls')),
    path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

In my spec file I was able to add the folder like this...

datas=[('..\\site\\staticfiles\\', '.\\staticfiles\\')]

And then in my html file I was able to use the static files like this...

<script src="{% static 'app/static.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'app/static.css' %}">

Hopefully this helps some people if they've run into the same problem. Also as a reminder be sure to run collectstatic before you build especially if you've modified or changed any of your static files.

python manage.py collectstatic

Cheers!

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐