CSS文件在我使用Django的生产模式时未加载。

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

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

问题

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

So I have split the settings into three separate 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).

urls.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, everything works fine.

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

英文:

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-2.html
匿名

发表评论

匿名网友

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

确定