首页 > 解决方案 > 无法加载 CSS Django IIS

问题描述

我已经在公司服务器上的 Microsoft IIS 上部署了我的 Web 应用程序。Web.config 文件已设置,应用程序正在以所有权限运行。我创建了虚拟目录(以启用静态文件服务,将静态别名映射到静态目录,C:/inetpub/wwwroot/PyWeb/static/)。无论我做什么,我都无法获得我的“blog/main.css”。CSS未加载,我收到错误:

Refused to apply style from 'http://localhost/static/blog/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

设置.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True

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

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

base.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
        <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="shortcut icon" href="/media/favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">

部分 href="/media/favicon.ico" 正在工作并且我的图标已加载。我试图删除 rel="stylesheet" 但它没有帮助。

另外,我运行了collectstatic:

C:\inetpub\wwwroot\PyWeb>python manage.py collectstatic
Starting Scheduler...

You have requested to collect static files at the destination
location as specified in your settings:

    C:\inetpub\wwwroot\PyWeb\static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

1 static file copied to 'C:\inetpub\wwwroot\PyWeb\static', 128 unmodified.

我在 settings.py 中添加了以下内容,但没有帮助:

import mimetypes
mimetypes.add_type("text/css", ".css", True)

我的媒体文件夹中的所有静态图像都加载没有问题,我只是我的 css 文件有问题。CGI 和静态内容在 Windows 功能中启用。

标签: pythoncssdjangoiis

解决方案


您可以尝试将 urls.py 中的 staticfiles_urlpatterns() 添加到您的主应用程序模块

from .site import admin
from django.urls import path, include
from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("auth2.urls")),
    url(r'^ckeditor/', include('ckeditor_uploader.urls')),
]

urlpatterns += staticfiles_urlpatterns()

推荐阅读