CSS Files Not Loading with Wrong MIME Type in Django
When encountering issues where CSS and JS files fail to load with an error indicating a wrong MIME type (e.g., "Resource interpreted as Stylesheet but transferred with MIME type application/x-css"), it's necessary to address this MIME type mismatch.
To resolve this issue in a Django environment, the following solution can be implemented:
Add MIME Type Mapping to settings.py
In your Django project's settings.py file, include the following snippet to explicitly map the MIME type for CSS files:
import mimetypes mimetypes.add_type("text/css", ".css", True)
Explanation:
This Python code uses the mimetypes module to add a mapping between the text/css MIME type and the .css file extension. This ensures that Django serves CSS files with the correct MIME type, which should resolve the loading issue.
Example:
Consider the following example HTML code:
<link href="/static/css/bootstrap.css" rel="stylesheet" type="text/css">
With the MIME type mapping added to settings.py, Django will correctly serve the bootstrap.css file with the text/css MIME type, allowing it to load as expected.
The above is the detailed content of Why Are My CSS and JS Files Not Loading with the Wrong MIME Type in Django?. For more information, please follow other related articles on the PHP Chinese website!