'Django TemplateDoesNotExist at '/' with outside app
Lately i've been trying to connect my django application that serves as an API to a react app that will work as the frontend (the react app was made with vite by the way). The issue that i'm having is that, no matter what i change in the index.html (frontend), urls.py or settings.py (backend) i always get the same error: TemplateDoesNotExist at /.
This would be my folder hierarchy, considering the react folder and django folder are at the same level (don't mind the name of the folders inside de hierarchy, i need to change them).
- React (front end):
This is the index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="https://va.exeiot.com/static/assets/media/logos/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--Fuenes Material UI-->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<!--Fuentes EXEIOT-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700">
<title>Video Analitica</title>
<!--Linea de refereencia para que el navegador pueda encontrar index.algo.js-->
<base href="/dist/">
<!--Fin referencia-->
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
- Django (backed, API):
In the Django directory the folder "backend" contains the settings of the django project and the folder "frontend" contains the api, views and models. This are the contents of:
- settings.py
import os
from pathlib import Path
import environ
# Environ
root = environ.Path(__file__) - 2
SITE_ROOT = root()
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
ENV_PATH = env.str('ENV_PATH', default=SITE_ROOT + '/.env')
environ.Env.read_env(ENV_PATH)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
REACT_BASE_DIR = Path(__file__).resolve().parent.parent.parent
# App url
APP_URL = env('APP_URL')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'not putting that here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
# 'frontend.apps.FrontendConfig', Modificado para compatibilidad con exe-va-plataforma-ui
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'frontend', # Añadido para compatibilidad con exe-va-plataforma-ui
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(REACT_BASE_DIR, 'exeiot-va-plataforma-ui', 'dist')],# Modificado para compatibilidad con exe-va-plataforma-ui
'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',
#'frontend.context_processors.app_url', Modificado para compatibilidad con exe-va-plataforma-ui
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': env('POSTGRES_DB'),
'USER': env('POSTGRES_USER'),
'PASSWORD': env('POSTGRES_PASSWORD'),
'HOST': 'db',
'PORT': 5432,
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'es-es'
TIME_ZONE = 'America/Santiago'
USE_I18N = True
USE_L10N = False
USE_TZ = True
DATE_FORMAT = 'd-m-Y'
DATE_INPUT_FORMATS = ['%d-%m-%Y']
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
"DATE_INPUT_FORMATS": ["%d-%m-%Y"],
"DATE_FORMAT": "%d-%m-%Y",
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = 'static/'# Modificado para compatibilidad con exe-va-plataforma-ui
STATICFILES_DIRS = [os.path.join(REACT_BASE_DIR, 'exeiot-va-plataforma-ui', 'dist', 'assets')]# Creado para compatibilidad con exe-va-plataforma-ui
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
- backend/urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from frontend.views import index
""" Modificado para compatibilidad con exeiot-va-plataforma-ui """
urlpatterns = [
path('', index, name="index"),
path('admin/', admin.site.urls),
# path('accounts/', include('django.contrib.auth.urls')), Comentado para compatibilidad con exeiot-va-plataforma-ui
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)#\
# + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
- frontend/urls.py:
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from frontend.forms import UserLoginForm
from . import views
from . import api
from .api_custom import api_dashboard
from .api_custom import api_entrenamiento
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'detecciones', views.DeteccionViewSet)
router.register(r'profiles', views.ProfileViewSet)
router.register(r'metadatas', views.MetadataViewSet)
router.register(r'datasets', views.DatasetViewSet)
router.register(r'modelos', views.ModeloViewSet)
router.register(r'clases', views.ClaseViewSet)
router.register(r'auditorias', views.AuditoriaViewSet)
urlpatterns = [
path('', views.index, name='index'),# ______________________________________________
# path('dashboard/', views.dashboard, name='dashboard'), | Comentado para compatibilidad
# path('procesamiento/', views.procesamiento, name='procesamiento'), | con exeiot-va-plataforma-ui
# path('entrenamiento/', views.entrenamiento, name='entrenamiento'), |
# path('entrenamiento_test/', views.entrenamiento_test, name='entrenamiento_test'), |
path('api/', include(router.urls)),
path('api/datasets/add', api_entrenamiento.datasets_add, name='api_entrenamiento.datasets_add'),
path('api/modelos/add', api_entrenamiento.modelos_add, name='api_entrenamiento.modelos_add'),
path('api/dashboard/general', api_dashboard.dashboard_general, name='api_dashboard.dashboard_general'),
path('api/dashboard/distribucion', api_dashboard.dashboard_distribucion, name='api_dashboard.dashboard_distribucion'),
path('api/dashboard/distribucion_clases', api_dashboard.dashboard_distribucion_clases, name='api_dashboard.dashboard_distribucion_clases'),
path('api/dashboard/distribucion_turnos', api_dashboard.dashboard_distribucion_turnos, name='api_dashboard.dashboard_distribucion_turnos'),
path('api/dashboard/distribucion_usuarios', api_dashboard.dashboard_distribucion_usuarios, name='api_dashboard.dashboard_distribucion_usuarios'),
path('api/dashboard/detalle_metadatas', api_dashboard.dashboard_detalle_metadatas, name='api_dashboard.dashboard_detalle_metadatas'),
path('api/detecciones/metadata', api.detection_2_metadata, name='api.detection_2_metadata'),
path('api/detecciones/upload', api.upload_detections, name='api.upload_detections'),
path('api/detections/tree', api.detections_tree, name='api.detections_tree'),
path('api/detections/data', api.detections_data, name='api.detections_data'),
path('api/metadatas/data', api.detections_data, name='api.metadatas_data'),
path('api/detections/params', api.detections_params, name='api.detections_params'),# __________
# path('accounts/login/', auth_views.LoginView.as_view(template_name='registration/login.html',|Comentado para compatibilidad
# authentication_form=UserLoginForm)), | con exeiot-va-plataforma-ui
]```
I read on a similar post that i probably need to add my react folder to installed apps, but i wouldn't know how to do that since the fact that the react folder is outside of the django root.
Any help is welcome and thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


