menu

Questions & Answers

Serve public files in django

I am using Django with React. And I want to serve react public files from Django.

but django static files are served with a prefix url, like this

/static/favicon.ico
/static/manifest.json

but I want to serve files like this, without any prefix.

/favicon.ico
/manifest.json
/serviceworker.js

So how do I do it? please help

Comments:
2023-01-21 00:55:07
Is that a good idea? What happens if a user uploads a file (to your media folder) with the same name of an existing URL path? You can make exceptions for files like favicon.ico and manifest.json in your web server (nginx etc) configuration.
2023-01-21 00:55:07
But what about development?
2023-01-21 00:55:07
Are you fussed about a missing favicon during development? If yes, you should use a proper web server during development too.
2023-01-21 00:55:07
@Selcuk , manifest.json!
2023-01-21 00:55:07
I want to test pwa, where we need manifest.json and serviceworker.js in the root path.
2023-01-21 00:55:07
You can always define URL redirects in your urls.py for those special cases, e.g. re_path(r'^manifest\.json$', RedirectView.as_view(url='/static/manifest.json', permanent=True)).
2023-01-21 00:55:07
I tried it but browser shows warning and does not allow it for PWA. But fortunately I have found a very good way to do this and answered it bellow. Thanks for helping.
Answers(2) :

I searched a lot about this and eventually found this as the best and efficient way

app/urls.py

import os
from django.urls import path
from django.conf import settings
from public import views

urlpatterns = []

SERVE_DIR = os.path.join(str(settings.BASE_DIR), "folder_path")
if os.path.exists(SERVE_DIR):
    files = os.listdir(SERVE_DIR)
    for f in files:
        urlpatterns += [path(f, views.public)]

app/views.py

import os
from django.conf import settings
from django.views.static import serve

def public(request, public_url):
    public_folder = os.path.join(str(settings.BASE_DIR), "folder_path")
    return serve(request, public_url, document_root=public_folder)
Comments:
2023-01-21 00:55:08
Good job! Solved my problem as well

Refer to Static Files

Changing STATIC_URL from '/static/' to '/' should work.

Comments:
2023-01-21 00:55:08
No, it does not work and shows error. It has security issue.
2023-01-21 00:55:08
Use a webserver to serve static files. Catch static files by using the extensions i.e .json
2023-01-21 00:55:08
that includes a lot of work and also not easeful during development.