How to resolve recursion error in python django urls.py - django

I'm pretty new to django and working on a project from https://github.com/mkaykisiz/DjangoS3Browser/ where I'm ending up with recursion error after adding "url(r'^' + settings.S3_BROWSER_SETTINGS + '/', include('djangoS3Browser.s3_browser.urls'))," line to url.py
Project structure:
I've the views under s3_browser dir and hence imported the same Can you correct me?Below is my project structure:
└───djangoS3Browser
└───manage.py
├───s3_browser
│ └───__pycache__
└─── operations.py
└─── settings.py
└─── urls.py
└─── views.py
└─── wsgi.py
├───static
│ ├───css
│ ├───images
│ └───js
├───templates
├───templatetags
URL.py
from django.conf.urls import url, include
from django.conf.urls.static import static
from djangoS3Browser.s3_browser import settings
from djangoS3Browser.s3_browser import views
import sys
urlpatterns = [
url(r'^get_folder_items/(.+)/(.+)/$', views.get_folder_items, name='get_folder_items'),
url(r'^upload/$', views.upload, name='upload'),
url(r'^create_folder/$', views.create_folder, name='create_folder'),
url(r'^download/$', views.download, name='download'),
url(r'^rename_file/$', views.rename_file, name='rename_file'),
url(r'^paste_file/$', views.paste_file, name='paste_file'),
url(r'^move_file/$', views.move_file, name='move_file'),
url(r'^delete_file/$', views.delete_file, name='delete_file'),
url(r'^' + settings.S3_BROWSER_SETTINGS + '/', include('djangoS3Browser.s3_browser.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Settings.py:
AWS_ACCESS_KEY_ID = ""
AWS_SECRET_ACCESS_KEY = ""
AWS_STORAGE_BUCKET_NAME = ""
AWS_S3_ENDPOINT_URL = ""
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
S3_BROWSER_SETTINGS = "djangoS3Browser"
AWS_EXPIRY = 60 * 60 * 24 * 7
control = 'max-age=%d, s-maxage=%d, must-revalidate' % (AWS_EXPIRY, AWS_EXPIRY)
AWS_HEADERS = {'Cache-Control': bytes(control, encoding='latin-1')}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS':
{
'libraries': {'s3-load': 'djangoS3Browser.templatetags.s3-tags',},
'context_processors': ["django.contrib.auth.context_processors.auth",'django.contrib.messages.context_processors.messages',]
}
}
]
SECRET_KEY = 'y130-j9oz4r5aoamn_n=+s-*7n)*3^s$jmf4(qw6ik28()g^(n'
DEBUG = True
ALLOWED_HOSTS = ['*']
ROOT_URLCONF= 'djangoS3Browser.s3_browser.urls'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
STATIC_URL = '{}/static/'.format(AWS_S3_ENDPOINT_URL)
STATIC_ROOT = '/static/'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangoS3Browser',
]
WSGI_APPLICATION = 'djangoS3Browser.s3_browser.wsgi.application'
MIDDLEWARE = (
'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',
)
Actual result:
File "C:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 162, in check
warnings.extend(self._check_pattern_startswith_slash())
File "C:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 125, in _check_pattern_startswith_slash
if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'):
RecursionError: maximum recursion depth exceeded while calling a Python object

You are importing wrong settings and views file. Just modify your code like:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from your_app import views
import sys
urlpatterns = [
url(r'^get_folder_items/(.+)/(.+)/$', views.get_folder_items, name='get_folder_items'),
url(r'^upload/$', views.upload, name='upload'),
url(r'^create_folder/$', views.create_folder, name='create_folder'),
url(r'^download/$', views.download, name='download'),
url(r'^rename_file/$', views.rename_file, name='rename_file'),
url(r'^paste_file/$', views.paste_file, name='paste_file'),
url(r'^move_file/$', views.move_file, name='move_file'),
url(r'^delete_file/$', views.delete_file, name='delete_file'),
url(r'^' + settings.S3_BROWSER_SETTINGS + '/', include('djangoS3Browser.s3_browser.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT: Instead of copying to your workspace, you need to install djangoS3Browser via pip and add it to your existing project. As in their github repo:
Just add as an application to a Django project, add some settings, and you'll be able to browse cloud containers and implied subdirectories, as well as view / download objects.
So you need to create a project in django by using django-admin startproject mysite command, then import djangoS3Browser as an app.

Related

Django custom management command not found

app/
├─ management/
│ ├─ commands/
│ │ ├─ customcommand.py
myfunction.py
site/
├─ settings.py
Content of settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '****'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
]
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 = 'site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
]
}
Content of customcommand.py
from django.core.management.base import BaseCommand, CommandError
import time
import requests
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def handle(self, *args, **options):
print("execued the commands success!!")
start_time = time.time()
for number in range(1, 50):
url = f'https://pokeapi.co/api/v2/pokemon/{number}'
resp = requests.get(url)
pokemon = resp.json()
print(pokemon['name'])
print("--- %s seconds ---" % (time.time() - start_time))
Contents of myfunction.py
from django.core import management
def funcA():
management.call_command('customcommand')
funcA()
On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config
Try adding __init__.py to management/ and commands/ directories.
I have solved the issue by adding the django.setup() call, after configuring the environment variable.
Inside myfunction.py, the following changes should be made
from django.core import management
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings')
django.setup()
def funcA():
management.call_command('customcommand')
funcA()
django.setup() is essential to include because it registers your applications and commands defined in your settings in a standalone script which the manage.py or django-admin takes care usually

Can't display images from models when debug=false

I have asked another question about the issue of displaying images from models. and It was because I didn't add media url to urlpatterns. But it turns out that it only works when I set debug=true in settings file, when I set debug=false, I got 404 error again, any expert here to help ? I need to set debug=false for production
here my urls.py file
from django.contrib import admin
from django.urls import path
from home import views as HomeViews
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
import os
urlpatterns = [
path('admin/', admin.site.urls),
path('',HomeViews.index,name='home')
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my settings file
from pathlib import Path
import os
import django_heroku
import django
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc#13'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'testimage.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'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',
],
},
},
]
WSGI_APPLICATION = 'testimage.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static")]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
django_heroku.settings(locals())
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
my models.py
from django.db import models
# Create your models here.
class Images(models.Model):
photo = models.ImageField(blank=True, null=True, default=None)
title = models.CharField(max_length=250)
def __str__(self):
return self.title
views and template
from django.shortcuts import render
from home.models import Images
# Create your views here.
def index(request):
images = Images.objects.all()
context = {
'images':images
}
return render(request,'home.html',context)
template
{%for i in images %}
<img src="{{MEDIA_URL}}{{i.photo.url}}" alt="">
{%endfor%}
Here's the error when set debug=false:
[15/Feb/2021 13:17:05] "GET /media/20210129_205930.jpg HTTP/1.1" 404 179
[15/Feb/2021 13:17:05] "GET /media/20201227_111422.jpg HTTP/1.1" 404 179
Please help me out. Many thanks !
I face the same problem
but I solve this problem using this code
pip install whitenoise
in settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / "media"
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
In urls.py
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
urlpatterns = [
path('user_area/', admin.site.urls),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('', include('main.urls')),
path('', include('user_area.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), ]
python manage.py collectstatic
Follow this code you will solve your problems
You should insert some ALLOWED_HOSTS in settings.py like :-
ALLOWED_HOSTS = ['*']
or Your website name :-
ALLOWED_HOSTS = ['your_website_name']

Django TemplateDoesNotExist at templates

I created new project and can't find where the place where mistake was made.
Django versiob - 3.1.5
Python 3.7.4
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['C:\Users\user\PycharmProjects\Django learning\Portfolio\landingpage',
'C:\Users\user\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\user\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\user\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\user\AppData\Local\Programs\Python\Python37',
'C:\Users\user\PycharmProjects\Django learning\Portfolio\venv',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg',
'C:\Users\user\PycharmProjects\Django '
'learning\Portfolio\venv\lib\site-packages\pip-19.0.3-py3.7.egg']
structure:
landingpage:
--forms #app:
urls
views
--landingpage:
templates:
index.html
settings.py
urls
others ...
landingpage/settings:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
project_name = "landingpage"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# apps
'forms',
]
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 = 'landingpage.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'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',
],
},
},
]
landingpage/urls:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('forms.urls')),
]
forms/urls:
from django.urls import path
from . import views
app_name = 'forms'
urlpatterns = [
path('', views.index, name='index')
]
views:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
landingpage/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
Don't put your templates in landingpage folder. You should put your Templates in your app forms
Try to use this :-
Make a new folder in forms named templates and then make a new folder in templates named forms.
Your structure of folders should be like this :-
forms -> templates -> forms -> index.html
Use this in your views.py :-
def index(request):
return render(request, 'forms/index.html')

Django: TemplateDoesNotExist at /

I am using Django 3.0.7 and have a project named starling and an app named piggybank. I placed my index.html inside templates/starling inside the piggybank directory
The following urls.py is inside piggybank:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
The urls.py in starling (project) is:
"""starling URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("", include("piggybank.urls")),
path('admin/', admin.site.urls),
]
My full settings.py:
"""
Django settings for starling project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')4^iro*2zhq%f9w2du33eu#ja%)&_cqltplq9b2lzu+qf#xz(6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'starling.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'starling.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
Template-loader post mortem:
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/admin/templates/starling/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/auth/templates/starling/index.html (Source does not exist)
And lastly an image of my directories:
To fix the problem, add piggybank to INSTALLED_APPS in your settings.
In your TEMPLATES setting, you have:
'APP_DIRS': True,
This is the default, and means that Django will look at the templates directory for each app in INSTALLED_APPS. In the post mortem you can see:
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/admin/templates/starling/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/anna/starling/lib/python3.6/site-packages/django/contrib/auth/templates/starling/index.html (Source does not exist)
It's not looking in the piggybank/templates directory because you haven't added piggybank to INSTALLED_APPS yet.
You need are missing TEMPLATES DIR
read this django templates
try this
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # your dir template path
I got this error when I forgot to add the app in installed apps:
INSTALLED_APPS = [
...
'app.apps.AppConfig',
...
]
app is the name of you app, so if your apps name was myApp,
then it would be: 'myApp.apps.MyappConfig',

All static assets coming back as "404 (Not found)" in Django/React app

My application sits at the server path /home/myapp/.
The static assets sit at /home/myapp/src/static/ when a python manage.py collectstatic is performed.
It copies assets from /home/myapp/src/assets/.
I have tried with DEBUG both True and False.
When I navigate to the web application at https://test.example.com, it tells me that all of the assets that reside at /home/mpapp/src/assets/ are 404 (Not Found) despite the files being there.
Also, my web server setup is Apache with a reverse proxy to Gunicorn. I'm serving the application with gunicorn wsgi which serves the application at 127.0.0.1:8000, which is where Apache is ProxyPass to. I've tested against a brand new Django application and this setup serves it properly, so it shouldn't be how Apache and Gunicorn are configured.
What I have been doing is:
1) npm start to compile the React front-end assets
2) python manage.py collectstatic to move the assets to /static/
3) Run gunicorn wsgi where the manage.py and wsgi.py reside
Some code would be helpful. Here is my settings.py:
import os
import sys
import json
import datetime
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
# Import JSON file
print(Path(__file__))
with open('./config/config.json') as f:
s = json.loads(f.read())
def get_settings(settings, s=s):
try:
return s[settings]
except KeyError:
error_msg = 'Set the {0} environment vaiable'.format(settings)
raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(2)
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_settings('SECRET_KEY')
ALLOWED_HOSTS = [
'*',
]
# Application definition
INSTALLED_APPS = [
# Base packages
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party packages
'rest_framework',
'rest_framework_jwt',
'webpack_loader',
'tinymce',
# Local packages
'authentication',
'documents',
'contact',
'home',
'results',
'users'
]
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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_settings('DEBUG')
WSGI_APPLICATION = 'wsgi.application'
# Password validation
AUTH_USER_MODEL = 'authentication.User'
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',
},
]
# REST Framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
# DRF JWT token settings
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_ALLOW_REFRESH': True,
}
# Webpack settings
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, './config/webpack-stats.json'),
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# EMAIL SETTINGS
EMAIL_HOST = get_settings('EMAIL_HOST')
EMAIL_HOST_USER = get_settings('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = get_settings('EMAIL_HOST_PASSWORD')
EMAIL_PORT = get_settings('EMAIL_PORT')
EMAIL_USE_TLS = True
My directory structure looks like the following which is based on Two Scoops:
testapp
assets
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
scss
config
config.json
settings.py
urls.py
webpack.config.js
react
index.jsx
static
admin
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
rest_framework
scss
templates
index.html
manage.py
wsgi.py
Also, my urls.py if that might be relevant:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
from home.views import GetHomeAPIView
urlpatterns = [
# Admin URL
url(r'^admin', admin.site.urls),
# API authentication entry point
url(r'^api/auth/', include('authentication.urls', namespace='signin')),
# API /home entry point
url(r'^api/home/', GetHomeAPIView.as_view(), name='home'),
# API /contact entry point
url(r'^api/contact/', include('contact.urls', namespace='contact')),
# API /contact entry point
url(r'^api/users/', include('users.urls', namespace='users')),
# Any requets that come through serve the index.html
url(r'^$', TemplateView.as_view(template_name='index.html')),
]
So not sure 100% what to do.
I have tried changing both STATIC_ROOT and STATIC_URL to the actual path /home/myapp/src/static/ which didn't do anything.
A bit stumped as to how to resolve this and the SO questions I have reviewed have not fixed the issue.
Well, I got things to start loading by doing the following in urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also can be read about here.
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development
It is working, but that being said, the sections is called "Serving static files during development"... I'm doing this for production.