当我在Django中使用生产模式时,CSS文件没有加载。

huangapple go评论152阅读模式
英文:

css files are not loaded when I am using production mode with Django

问题

我有一个Django应用程序,我试图模拟生产环境。

所以我将设置分为三个单独的文件:local、prod和base。

base.py的一部分如下所示:

import os
from pathlib import Path
from os import environ
from dotenv import load_dotenv

load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG') == "False"

STATIC_URL = '/static/'
STATIC_DIRS = [
     (BASE_DIR, 'static')
]
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = ['zijn']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_ROOT = BASE_DIR/'media'
MEDIA_URL = '/media/'

manage.py文件如下所示:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from zijn.settings import base

def main():
    """Run administrative tasks."""
    if base.DEBUG:
       os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local')
    else:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production')
  
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

如果将DEBUG设置为False,这将起作用。我得到以下输出:

Django version 4.2.3, using settings 'zijn.settings.production'
Starting development server at http://127.0.0.1:8080/

但在生产模式下,CSS没有加载。在开发工具中,我看到以下错误:

GET http://127.0.0.1:8080/static/admin/js/theme.js

GET http://127.0.0.1:8080/static/admin/js/nav_sidebar.js

The resource from “http://127.0.0.1:8080/static/admin/js/theme.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
admin
The resource from “http://127.0.0.1:8080/static/admin/js/nav_sidebar.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

url.py文件如下所示:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from drf_spectacular.views import (SpectacularAPIView, SpectacularSwaggerView)
from rest_framework.schemas import get_schema_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('zijnAdmin.urls')),         
    path('api-auth/', include('rest_framework.urls')),
    path('schema/', get_schema_view()),
    path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
    path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'),
    path('api/user/', include('accounts.urls'))    
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
   + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

在本地模式下一切正常。

问题:如何在生产模式下加载CSS?

英文:

I have a django app. And I try to simulate production envrionment.

So I have splitted the settings in three seperate files: local , prod and base.

Part of the base.py looks like:

import os
from pathlib import Path
from os import environ
from dotenv import load_dotenv

load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG') == "False"



STATIC_URL = '/static/'
STATIC_DIRS = [
     (BASE_DIR, 'static')
]
STATIC_ROOT = BASE_DIR /'staticfiles'
STATICFILES_DIRS =['zijn']

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR /'media'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_ROOT = BASE_DIR/'media'
MEDIA_URL = '/media/'

And the manage.py file looks like:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from zijn.settings import base



def main():
    """Run administrative tasks."""
    
    if base.DEBUG:
       os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local')
    else:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production')
  
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

And this works if I set DEBUG to False. I get this output:

Django version 4.2.3, using settings 'zijn.settings.production'
Starting development server at http://127.0.0.1:8080/

But in production mode the css is not loaded. in dev tools I see the following errors:

GET
http://127.0.0.1:8080/static/admin/js/theme.js

GET
http://127.0.0.1:8080/static/admin/js/nav_sidebar.js

The resource from “http://127.0.0.1:8080/static/admin/js/theme.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
admin
The resource from “http://127.0.0.1:8080/static/admin/js/nav_sidebar.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

url.py:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from drf_spectacular.views import (SpectacularAPIView, SpectacularSwaggerView)

from rest_framework.schemas import get_schema_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('zijnAdmin.urls')),         
    path('api-auth/', include('rest_framework.urls')),
    path('schema/', get_schema_view()),
    path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
    path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'),
    path('api/user/',include('accounts.urls') )    
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
   + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


in local mode everyting works fine.

Question: So how to run Production mode with the css loaded?

答案1

得分: 1

默认情况下,Django在生产模式下无法从本地环境访问静态文件和媒体文件。

可以使用AWS、Wasabi、Blackblaze或Azure Bucket来存储静态文件和上传的媒体文件。

英文:

By default django in production mode cant access static and media file from local env.

Use AWS, Wasabi, Blackblaze or Azure Bucket to store your static files and uploaded media files

答案2

得分: 1

默认情况下,Django不负责提供静态文件的服务。你需要自己处理这个问题。你可以使用第三方服务,如AWSS3、bunnyCDN等来处理。你也可以配置你的nginx或apache服务器来从你自己的服务器上提供静态文件。

然而,如果你仍然在本地测试你的代码,可以尝试将静态URL添加到你的urlpatterns中,这可能会解决你的问题。

from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
英文:

By default Django is not responsible for serving your static files. You need to handle that by yourself. You can do that by using any third party services like AWSS3, bunnyCDN etc. You can also configure your nginx or apache server to serve static files from your own server.

However If you are still trying to test your code on localhost, try Adding static url to your urlpatterns. this might solve your problem

from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

huangapple
  • 本文由 发表于 2023年8月9日 16:32:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定