代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

在Django中被困在设置CSS静态文件中

  •  1
  • Cheok Yan Cheng  · 技术社区  · 7 年前

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

    我有以下目录结构

    app
     |
     |- manage.py
     |- requirements.txt
     |- static
     |     |
     |     |- css
     |         |
     |         |- snapweb.css
     |
     |
     }- templates
     |- web
         |
         |- __init__.py
         |- settings.py
         |- urls.py
         |- wsgi.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()
    

    /应用程序/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:
    

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

    以下URL有效。我没想到会成功,因为我看不出来 /app/static/admin/css/base.css 文件存在。

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

    我也很困惑,因为下面的URL不起作用。即使文件 /app/static/css/snapweb.css 为什么Django不去拿文件?

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

    我希望两个网址, https://localhost:2053/static/admin/css/base.css https://localhost:2053/static/css/snapweb.css 会有用的。 我错过了什么安排吗?

    还有,我怎么跑 python manage.py集合静态 /app/static ?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Zags    7 年前

    首先,你似乎忽略了应用程序和项目之间的django区别(假设你将项目命名为“app”)。这个项目 manage.py settings.py . 这些应用程序 models.py

    考虑到你使用的是来自管理应用的静态文件以及你自己的静态文件,你需要做一些重组。Django正在查找 STATIC_ROOT . 在“正确”的设置中,您应该将静态文件放在特定于应用程序的目录中(与项目相反)。项目静态文件(指向 应该没有定义任何内容,因为Django将在运行时放置所有文件 collectstatic

    尝试将静态文件夹移动到应用程序文件夹的子目录(“web/static”)并运行 收藏家 .

    docs