在vercel中部署django网页时未加载静态文件(使用whitenoise)

问题描述 投票:0回答:1

when the project is deployed shows this error 这是我的设置.py:

import os
from pathlib import Path

# 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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^30@=wx2m&2q6l48hxb*y6c%0negga@@eixcj5%-rn^3yzo#^k'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'me',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    "whitenoise.runserver_nostatic",
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    "whitenoise.middleware.WhiteNoiseMiddleware",
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Matheus.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Matheus.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / "staticfiles" / "static"

if DEBUG:
    STATICFILES_DIRS=['staticfiles']
    STATIC_ROOT = None
else:
    STATICFILES_DIRS=[]
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Whitenoise Storage Class  - Apply compression but don’t want the caching behaviour
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

这是我的 vercel.json:

{
  "version": 2,
  "builds": [
      {
          "src": "Matheus/wsgi.py",
          "use": "@vercel/python",
          "config": {
              "maxLambdaSize": "15mb",
              "runtime": "python3.12"
          }
      },
      {
          "src": "build.sh",
          "use":"@vercel/static-build",
          "config":{
              "distDir": "staticfiles"
          }
      }
  ],
  "routes": [
      {
          "src":"/static/(.*)",
          "dest":"/static/$1"
      },
      {
          "src": "/(.*)",
          "dest": "Matheus/wsgi.py"
      }
  ]
}

这是我的build.sh:

#!/bin/bash

# Update pip
echo "Updating pip..."
python3.12 pip install -U pip

# Install dependencies

echo "Installing project dependencies..."
python3.12 -m pip install -r requirements.txt

# Make migrations
echo "Making migrations..."
python3.12 manage.py makemigrations --noinput
python3.12 manage.py migrate --noinput
#Install whitenoise
echo Installing white noise..."
python3.12 manage.py whitenoise
# Collect staticfiles
echo "Collect static..."
python3.12 manage.py collectstatic --noinput --clear

echo "Build process completed!"```

wsgi config :

导入操作系统

从 django.core.wsgi 导入 get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Matheus.settings')

应用程序 = get_wsgi_application()

vercel 配置

app = application # 添加此行。

https://github.com/Matheus-Dimon/me/tree/teste


I want to a config to change that can make the deploy serves the staticfiles.
python django web deployment static
1个回答
0
投票

当 Debug 为 False 时我是这样做的...

在 urls.py 中(主要的)

from django.conf import settings
from django.views.static import serve
from django.contrib import admin
from django.urls import path, include, re_path


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
    re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

    re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

对于settings.py...我这样做了:


STATIC_URL = '/static/'

MEDIA_URL = '/media/'



if DEBUG:

  STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

else:

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



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

如果 Debug 为 True,则这样做... urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


设置.py

import os
...
...
...
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static/']
MEDIA_URL = '/media/'

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


© www.soinside.com 2019 - 2024. All rights reserved.