import os from django.contrib import admin from django.http import HttpResponseNotFound from django.urls import include, path, re_path from django.views.generic import RedirectView, TemplateView from django.views.static import serve as static_serve from django.conf import settings from meals.views_spa import spa_serve from meals.views_dashboard import dashboard_api from meals.views_spa import _get_frontend_dir def _serve_fe_assets(request, path=''): """Serve built React assets (JS/CSS) from the frontend directory.""" fdir = _get_frontend_dir() rel = os.path.join('assets', path) target = os.path.normpath(os.path.join(fdir, rel)) if target.startswith(os.path.normpath(fdir)) and os.path.isfile(target): return static_serve(request, rel, document_root=fdir) return HttpResponseNotFound('Not found') urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='index'), path('app/', spa_serve, name='spa_serve'), path('app/', spa_serve, name='spa_serve_path'), re_path(r'^assets/(?P.+)$', _serve_fe_assets, name='fe_assets'), path('admin/', admin.site.urls), path('api/', include('meals.urls')), path('api/dashboard/', dashboard_api, name='dashboard_api'), path('dashboard/', RedirectView.as_view(url='/admin/', permanent=False), name='dashboard_redirect'), ] # When DEBUG is off (e.g. desktop.py / EXE mode), serve static files directly # so the Django admin and Jazzmin theme load correctly. if not settings.DEBUG: from django.contrib.staticfiles import finders as _sf_finders def _serve_static(request, path=''): """Search all static file roots for the requested path.""" for root in _static_roots: target = os.path.normpath(os.path.join(root, path)) if target.startswith(root) and os.path.isfile(target): return static_serve(request, path, document_root=root) from django.http import Http404 raise Http404 _static_roots = [] for _d in settings.STATICFILES_DIRS: if os.path.isdir(_d): _static_roots.append(os.path.normpath(_d)) for _finder in _sf_finders.get_finders(): for _path, _storage in _finder.list([]): _loc = getattr(_storage, 'location', None) if _loc and os.path.isdir(_loc): _static_roots.append(os.path.normpath(_loc)) urlpatterns += [ re_path(r'^static/(?P.+)$', _serve_static), ]