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

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

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:

  1. import os
  2. from pathlib import Path
  3. from os import environ
  4. from dotenv import load_dotenv
  5. load_dotenv()
  6. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  7. BASE_DIR = Path(__file__).resolve().parent.parent
  8. # Quick-start development settings - unsuitable for production
  9. # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
  10. # SECURITY WARNING: keep the secret key used in production secret!
  11. SECRET_KEY = os.environ.get('SECRET_KEY')
  12. # SECURITY WARNING: don't run with debug turned on in production!
  13. DEBUG = os.environ.get('DEBUG') == "False"
  14. STATIC_URL = '/static/'
  15. STATIC_DIRS = [
  16. (BASE_DIR, 'static')
  17. ]
  18. STATIC_ROOT = BASE_DIR / 'staticfiles'
  19. STATICFILES_DIRS = ['zijn']
  20. MEDIA_URL = '/media/'
  21. MEDIA_ROOT = BASE_DIR / 'media'
  22. # Default primary key field type
  23. # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
  24. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  25. MEDIA_ROOT = BASE_DIR/'media'
  26. MEDIA_URL = '/media/'

And the manage.py file looks like:

  1. #!/usr/bin/env python
  2. """Django's command-line utility for administrative tasks."""
  3. import os
  4. import sys
  5. from zijn.settings import base
  6. def main():
  7. """Run administrative tasks."""
  8. if base.DEBUG:
  9. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local')
  10. else:
  11. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production')
  12. try:
  13. from django.core.management import execute_from_command_line
  14. except ImportError as exc:
  15. raise ImportError(
  16. "Couldn't import Django. Are you sure it's installed and "
  17. "available on your PYTHONPATH environment variable? Did you "
  18. "forget to activate a virtual environment?"
  19. ) from exc
  20. execute_from_command_line(sys.argv)
  21. if __name__ == '__main__':
  22. main()

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

  1. Django version 4.2.3, using settings 'zijn.settings.production'
  2. 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:

  1. GET http://127.0.0.1:8080/static/admin/js/theme.js
  2. GET http://127.0.0.1:8080/static/admin/js/nav_sidebar.js
  3. 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).
  4. admin
  5. 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:

  1. from django.conf import settings
  2. from django.conf.urls.static import static
  3. from django.contrib import admin
  4. from django.urls import include, path
  5. from drf_spectacular.views import (SpectacularAPIView, SpectacularSwaggerView)
  6. from rest_framework.schemas import get_schema_view
  7. urlpatterns = [
  8. path('admin/', admin.site.urls),
  9. path('api/', include('zijnAdmin.urls')),
  10. path('api-auth/', include('rest_framework.urls')),
  11. path('schema/', get_schema_view()),
  12. path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
  13. path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'),
  14. path('api/user/', include('accounts.urls'))
  15. ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
  16. + 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:

  1. import os
  2. from pathlib import Path
  3. from os import environ
  4. from dotenv import load_dotenv
  5. load_dotenv()
  6. # Build paths inside the project like this: BASE_DIR / 'subdir'.
  7. BASE_DIR = Path(__file__).resolve().parent.parent
  8. # Quick-start development settings - unsuitable for production
  9. # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
  10. # SECURITY WARNING: keep the secret key used in production secret!
  11. SECRET_KEY = os.environ.get('SECRET_KEY')
  12. # SECURITY WARNING: don't run with debug turned on in production!
  13. DEBUG = os.environ.get('DEBUG') == "False"
  14. STATIC_URL = '/static/'
  15. STATIC_DIRS = [
  16. (BASE_DIR, 'static')
  17. ]
  18. STATIC_ROOT = BASE_DIR /'staticfiles'
  19. STATICFILES_DIRS =['zijn']
  20. MEDIA_URL = '/media/'
  21. MEDIA_ROOT = BASE_DIR /'media'
  22. # Default primary key field type
  23. # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
  24. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  25. MEDIA_ROOT = BASE_DIR/'media'
  26. MEDIA_URL = '/media/'

And the manage.py file looks like:

  1. #!/usr/bin/env python
  2. """Django's command-line utility for administrative tasks."""
  3. import os
  4. import sys
  5. from zijn.settings import base
  6. def main():
  7. """Run administrative tasks."""
  8. if base.DEBUG:
  9. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.local')
  10. else:
  11. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zijn.settings.production')
  12. try:
  13. from django.core.management import execute_from_command_line
  14. except ImportError as exc:
  15. raise ImportError(
  16. "Couldn't import Django. Are you sure it's installed and "
  17. "available on your PYTHONPATH environment variable? Did you "
  18. "forget to activate a virtual environment?"
  19. ) from exc
  20. execute_from_command_line(sys.argv)
  21. if __name__ == '__main__':
  22. main()

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

  1. Django version 4.2.3, using settings 'zijn.settings.production'
  2. 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:

  1. GET
  2. http://127.0.0.1:8080/static/admin/js/theme.js
  3. GET
  4. http://127.0.0.1:8080/static/admin/js/nav_sidebar.js
  5. 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).
  6. admin
  7. 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:

  1. from django.conf import settings
  2. from django.conf.urls.static import static
  3. from django.contrib import admin
  4. from django.urls import include, path
  5. from drf_spectacular.views import (SpectacularAPIView, SpectacularSwaggerView)
  6. from rest_framework.schemas import get_schema_view
  7. urlpatterns = [
  8. path('admin/', admin.site.urls),
  9. path('api/', include('zijnAdmin.urls')),
  10. path('api-auth/', include('rest_framework.urls')),
  11. path('schema/', get_schema_view()),
  12. path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'),
  13. path('api/docs', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'),
  14. path('api/user/',include('accounts.urls') )
  15. ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
  16. + 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。这可能会解决您的问题。

  1. from django.contrib import admin
  2. from django.conf.urls.static import static
  3. from django.conf import settings
  4. from django.urls import path
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. ]
  8. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  9. 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

  1. from django.contrib import admin
  2. from django.conf.urls.static import static
  3. from django.conf import settings
  4. from django.urls import path
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. ]
  8. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  9. 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:

确定