【问题标题】:Why doesen't css file apply on html file - Django为什么css文件不适用于html文件 - Django
【发布时间】:2019-01-17 01:22:19
【问题描述】:

我有一个问题,我的 .css 文件不适用于 Django 中的 .html 文件。但是,例如,当我键入 . .html 文件中的一些类名,pycharm 让我完成类名。所以,我认为它是正确的。

不管怎样,我把我的设置文件放进去:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

运行python manage.py collectstatic 成功并使用命令将我的 .css 文件添加到 .html:

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"/>

在我的项目中,我有这样的东西:

-website
   -static
        -admin (generated when I run the command above)
        -images
        -base.css
    -templates
        -navbar.html
        -base.html
     -app1
     -app2
     -etc

出于测试目的,我只是将简单的 div 放在 .html 文件的头部:

 <div class="example">jvhgbhjgf</div>

在 .css 文件中:

.example { background-color: red; border-radius: 15px;}

【问题讨论】:

    标签: html css django django-templates django-staticfiles


    【解决方案1】:

    在您的 urls.py 文件中添加以下代码:

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

    【讨论】:

    • 还是一样,什么都没发生。 :(
    • 在我完成了您在之前回复中所写的操作后,我可以访问,但仍然没有应用于 .html 文件。
    • 重启服务器成功!谢谢你,你让我开心! :)
    • 我还有一个问题.. 现在在每个应用程序中,我应该创建目录:static/static_dirs/name_of_app/my css 文件并在 .html 文件中链接它:{% load staticfiles % }
    • 我问这个,因为这种方法在我的应用程序中不适合我
    【解决方案2】:

    更改您的 settings.py 文件,如下所示:

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
    
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR), 'static', 'static_dirs'),
        )
    

    和目录树:

    -website
    -static
        -static_root
            -admin (generated when I run the command above)
        -static_dirs
            -images
            -base.css
    -templates
        -navbar.html
        -base.html
     -app1
     -app2
     -etc
    

    在 static_dirs 文件夹中添加 base.css 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      相关资源
      最近更新 更多