I setup a Swagger configuration on my Django project for a specific endpoint
It worked fully completed on my local machine but when I sent it on server it seems that the static files of drf_yasg cannot be collected and show there were a blank page without any 404 Not Found error, but also on the console it wrote the Js and CSS files are 404 not found
swagger.py
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from django.urls import path
from requests_app.views import RequestsVS
from rest_framework import permissions
single_endpoint_schema_view = get_schema_view(
openapi.Info(
title="/api/",
default_version='v1',
description="برای احراز هویت نیاز است تا کلید دریافتی در هدر درخواست ها با عنوان زیر ارسال شود",
),
public=True,
permission_classes=[permissions.AllowAny],
patterns=[path('requests/add/outside/', RequestsVS.as_view({'post': 'create_from_outside'}))],
)
swagger_urlpatterns = [
path('swagger/', single_endpoint_schema_view.with_ui('swagger', cache_timeout=0),
name='schema-swagger-ui'),
path('redoc/', single_endpoint_schema_view.with_ui('redoc', cache_timeout=0),
name='schema-redoc'),
]
urlpatterns = swagger_urlpatterns + [
]
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/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'
AUTH_USER_MODEL = 'users.User'
# Swagger settings
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False, # Set this to True if you're using session authentication
'SECURITY_DEFINITIONS': {
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header',
},
},
}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += swagger_urlpatterns
Actually on DEV/STAGING server it will work on static of env:
try to run: python manage.py findstatic --verbosity 2 static
and then
cp -r /env/lib/python3.11/site-packages/drf_yasg/static/drf-yasg/ /static/
or using django_static_whitenoise https://www.w3schools.com/django/django_static_whitenoise.php