卡在Django中设置CSS静态文件



我曾尝试在Django中设置静态文件,但失败了。

我有以下目录结构

app
|
|- manage.py
|- requirements.txt
|- static
|     |
|     |- css
|         |
|         |- snapweb.css
|
|
}- templates
|- web
|
|- __init__.py
|- settings.py
|- urls.py
|- wsgi.py
/

app/web/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
import logging
urlpatterns = [
path('', TemplateView.as_view(template_name='home.html'), name='home'),
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
/

app/web/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

请注意,我没有跑python manage.py collectstatic.因为,如果我想运行,我会得到以下警告,我不知道如何解决它。

/app # python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:
/app/static
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel:

所以,我的问题是,我对我的应用程序行为感到困惑。

以下网址有效。我没想到它会起作用,因为我看不到/app/static/admin/css/base.css文件存在。Django 从哪里获取文件?

https://localhost:2053/static/admin/css/base.css

我也感到困惑,因为以下 URL 不起作用。即使文件/app/static/css/snapweb.css在那里。为什么 Django 不拿起文件?

https://localhost:2053/static/css/snapweb.css

我希望两个 URL、https://localhost:2053/static/admin/css/base.csshttps://localhost:2053/static/css/snapweb.css都能正常工作。我错过了什么设置吗?

另外,如何在不覆盖/app/static的情况下成功运行python manage.py collectstatic

首先,你似乎错过了应用程序和项目之间的django区别(假设你已经将你的项目命名为"app"(。 该项目具有manage.pysettings.py。 这些应用程序具有models.py文件。

鉴于您使用的是来自管理应用程序的静态文件以及您自己的静态文件,您将需要进行一些重组。 Django 正在寻找STATIC_ROOT中的静态文件。 在"正确"的设置中,您应该将静态文件放在特定于您的应用程序(而不是您的项目(的目录中。 项目静态文件(由STATIC_ROOT指向(应该没有你在其中定义的任何内容,因为当你运行collectstatic时,Django 将把所有文件放在那里。

尝试将静态文件夹移动到应用程序文件夹的子目录("web/static"(并运行collectstatic

有关详细信息,请参阅文档。

最新更新