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
I think it can be fixed with one of the following:
1 - Make sure that
drf_yasgis installed on your server, if not you can use this command to install it2 - Verify that the static files are being served correctly on the server. Ensure that the web server configuration is correctly set up to serve static files. If you're using Django's development server (manage.py runserver), it automatically serves static files when the
DEBUGsetting is set toTrue. However, in a production environment, you may need to configure your web server (e.g.,NginxI do use it personally) to serve static files.You can do so by adding this block to your
Nginxconfiguration file:3 - Clear the static files cache on the server. Sometimes, cached files may cause issues. You can try running the following command on the server to clear the cache: