【问题标题】:Django development server. CSS files being served as 'text/html'Django 开发服务器。 CSS 文件作为“文本/html”提供
【发布时间】:2015-09-22 02:45:52
【问题描述】:

我正在使用 Django 1.8。我的两个 css 文件的状态均为 200,但 Firefox 显示:

The stylesheet http://localhost:8000/css/full-width-pics.css was not loaded because its MIME type, "text/html", is not "text/css". localhost:8000
The stylesheet http://localhost:8000/css/mainstyle.css was not loaded because its MIME type, "text/html", is not "text/css". localhost:8000

无论出于何种原因,这些文件都以 text/html 而不是 text/css 的形式提供。这是我的html。

  <link href="css/full-width-pics.css" rel="stylesheet" type="text/css" />
    <link href="css/mainstyle.css" rel="stylesheet" type="text/css" />

这是在 base.html 文件中。我在我的 index.html 文件中扩展了 base.html。在我开始使用模板继承并在 index.html 中包含所有内容之前,它运行良好。

我在 Ubuntu 上。我检查了 /etc/mime.types。 css 与 text/css 一起列出。

这让我很困惑

【问题讨论】:

  • /etc/mime.types 是系统本身的,它不一定被应用程序使用。您可以查看 Django 的设置。 this question 有帮助吗?
  • 我也试过了。它对我不起作用。我在 stackoverflow 的某个地方读到 Django 使用依赖于系统 mime 类型的 Python 的 Mime 类型。
  • 你的设置DEBUG = False ?
  • 你的url配置是什么?您是否检查过开发环境的此配置:docs.djangoproject.com/en/1.8/howto/static-files/…
  • 你能分享你的urlconf吗?

标签: python html css django django-dev-server


【解决方案1】:

2020 年答案:

如果您希望浏览器自动检测任何 mime 内容类型,这就是解决方案。

经过多次失败的静态尝试,这是动态解决方案。

def fetch(request):
    import mimetypes
    clientRequestUrl=os.getcwd()+'/servlet'+request.path
    try: return HttpResponse(fread(clientRequestUrl), content_type=mimetypes.guess_type(request.path)[0])
    except Exception as e: return HttpResponse(str(e)+'===> Error Thrown <br>')
  • 这里 fread() 直接读取文件在 try 中除了阻塞它只是一个 I/O 包装器
  • 在 try 块中 --> content_type=mimetypes.guess_type(request.path)[0] 执行 MIME 检测魔法 [0] 即第一个元素是必需的,因为它首先返回一个元组mime 类型,其次是编码。
  • request.path 在上面的行中被传递,因为它根据文件路径猜测 MIME。例如,如果客户端(浏览器)请求,则为名为 stylsheet.css 的文件的 text/css。
  • clientRequestUrl = 客户端尝试向服务器请求的确切 url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2012-03-01
    • 2012-12-03
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    相关资源
    最近更新 更多