【问题标题】:importing app css in Django在 Django 中导入应用程序 css
【发布时间】:2014-06-22 04:47:59
【问题描述】:

我不确定如何将 css 包含到我的 html 中。我的项目中有一个应用程序,它有自己的模板文件夹。我想将sample.css 放入我的html。

<link rel="stylesheet" type="text/css" href="{% %}"> 中的一些东西

不太确定在{% %}之间放什么

结构:

/proj
   /app
      /templates
         sample.css
         sample.html

这是我的模板目录:

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,'templates'),
    os.path.join(BASE_DIR,'home/templates'),
    os.path.join(BASE_DIR,'gallery/templates'),
    os.path.join(BASE_DIR,'contact/templates'),
    os.path.join(BASE_DIR,'aboutme/templates'),
)

如果需要任何其他信息。请告诉我!

更新结构

/proj
   /app
      /static
         /css
            sample.css
      /templates
         sample.html

【问题讨论】:

    标签: css django django-templates static-files


    【解决方案1】:

    css 文件以及js 文件和图像被视为static files

    通常的做法是使用django.contrib.staticfiles内置django app来管理静态文件。

    如果您正确设置应用程序,您的link 将如下所示:

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

    【讨论】:

    • @Liondancer 你也应该把css 文件放在其他文件夹中。将它们放在名为 app/static/css 的文件夹中是一种常见模式。
    • @RaydelMiranda 所以将我的模板重命名为静态?
    • @Liondancer 不要混淆templatesstatic files。这是您的应用程序的两个完全独立的部分。模板位于templates 目录中,静态文件位于static 目录中。
    • @crozzfire 是的,这更好,但是对于初学者来说,OP 至少应该分离模板和静态文件并将其配置为工作。你知道,第一次让它工作可能具有挑战性。
    • @Liondancer,你还在等什么!?这对我来说是一个可靠的答案。 ;)
    【解决方案2】:

    正如@alecxe 提到的,将它们放在一个名为 static 的文件夹中,并将它们包含在您的设置文件中。

    STATIC_URL = '/static/'
    
    # Additional locations of static files
    STATICFILES_DIRS = (
        # Put strings here, like "/home/html/static" or "C:/www/django/static".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
    )
    
    # List of finder classes that know how to find static files in
    # various locations.
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
    )
    

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多