Regarding Django error message TemplateDoesNotExist at / - django

I am trying to do an application for a blog by Django, but the top page (post_list.html) is not displayed.
The following error message will be displayed.
TemplateDoesNotExist at /
blogapp3/post_list.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.11.4
Exception Type: TemplateDoesNotExist
Exception Value:
blogapp3/post_list.html
Exception Location: F:\01_pro\kaso3\lib\site-packages\django\template\loader.py in select_template, line 53
Python Executable: F:\01_pro\kaso3\Scripts\python.exe
Python Version: 3.6.2
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\admin\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\kaso3\lib\site-packages\django\contrib\auth\templates\blogapp3\post_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: F:\01_pro\blogpro3\blogapp3\templates\blogapp3\post_list.html (Source does not exist)
I had been pointed out that the file structure is wrong from other websites, but I think this file doesn't seem to be strange. File structure is as follows.
F:\01_PRO\BLOGPRO3
│ db.sqlite3
│ manage.py
│
├─blogapp3
│ │ admin.py
│ │ apps.py
│ │ forms.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├─migrations
│ │ │ 0001_initial.py
│ │ | 0002_auto_20170905_1930.py
│ │ └─ __init__.py
│ │
│ │
│ ├─static
│ │ ├─css
│ │ │ blog.css
│ │ │
│ │ └─js
│ │
│ └─templates
│ ├─blog
│ │ about.html
│ │ base.html
│ │ comment_form.html
│ │ post_confirm_delete.html
│ │ post_detail.html
│ │ post_draft_list.html
│ │ post_form.html
│ │ post_list.html
│ │
│ └─registration
│ login.html
│
│
└─blogpro3
settings.py
urls.py
wsgi.py
__init__.py
Below, I display urls.py, views.py, settings.py in order to solve this issue.
blogpro3/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'',include('blogapp3.urls')),
url(r'^accounts/login/$', views.login, name='login'),
url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}),
]
blogapp3/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name='post_list'),
url(r'^about/$',views.AboutView.as_view(),name='about'),
url(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
url(r'^post/new/$',views.CreatePostView.as_view(),name='post_new'),
url(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$',views.PostDetailView.as_view(),name='post_remove'),
url(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'),
url(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.contrib.auth.decorators import login_required
from blogapp3.models import Post,Comment
from django.utils import timezone
from blogapp3.forms import PostForm,CommentForm
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostDleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')
##################################
##################################
#login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
post.publish()
return redirect('post_detail',pk=pk)
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
#login_required
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk)
settings.py
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__)))
TEMPLATE_DIRS = os.path.join(BASE_DIR,'blogapp3/templates/blog')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# 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',
'blogapp3.apps.BlogappConfig',
]
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 = 'blogpro3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_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 = 'blogpro3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'Static')
LOGIN_REDIRECT_URL = '/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)
What I am paying attention to is the following part in the error message.
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: F:\01_pro\blogpro3\blogapp3\templates\blog\blogapp3\post_list.html (Source does not exist)
The above path should be correct for following path.
F:\01_pro\blogpro3\blogapp3\templates\blog\post_list.html
However, I don't know how to fix above path.
I am glad if you tell me how to solve this issue.

Your file structure confirms exactly what the error says: there is no templates directory named "blogapp3", so there is no template named "blogapp3/post_list.html".
You should move your templates into the "blogapp3" directory.

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

Django DEBUG False not working in the Production Environment

I am new to Django and Python world, I am currently working on an Dajngo site, which is hosted on a Ubuntu20.04 VM. Upon hosting the site to the production, I noticed that, although the DEBUG is set to False in the prodiuction settings. I still see the Django DEBUG erros as if the DEBUG is set to True .
When I run python manage.py runserver command on the VM I get the below error.
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
Folder structure
.
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-310.pyc
│ ├── urls.cpython-310.pyc
│ ├── views.cpython-310.pyc
│ └── wsgi.cpython-310.pyc
├── settings
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-310.pyc
│ │ ├── base.cpython-310.pyc
│ │ ├── local.cpython-310.pyc
│ │ └── production.cpython-310.pyc
│ ├── base.py
│ ├── local.py
│ └── production.py
base.py (Common settings)
import os
from os.path import dirname, join
import posixpath
from posixpath import join
from pathlib import Path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '393266f4-9cc7-4cfe-96a8-2f2809e53e32'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#ALLOWED_HOSTS = []
# Application references
INSTALLED_APPS = [
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'AssayBlog',
'AssayCMS',
'ckeditor',
'ckeditor_uploader',
]
# Middleware 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 = 'AssaySite.urls'
# Template configuration
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 = 'AssaySite.wsgi.application'
# Database
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
#}
# Password validation
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
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# HTTPS SETTINGS
SESSIONS_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True #False
SECURE_SSL_REGIRECT = True
# HSTS SETTINGS
SECURE_HSTS_SECONDS = 31536000 # 1 YEAR
SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
CKEDITOR_UPLOAD_PATH = "uploads/"
production.py
from AssaySite.settings.base import *
DEBUG = False
ALLOWED_HOSTS = [
'www.exampl.com',
'example.com',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'abssaysitedb',
'USER': 'admingres',
'PASSWORD': 'password',
'HOST': '192.168.1.201',
'PORT': '8686',
}
}
local.py
from AssaySite.settings.base import *
DEBUG = False
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': 'localhost',
'PORT': '5432',
}
}
I have carefully reviewed the settings code to see if the DEBUG is True in any part of my code but everything looks good.
Please help
You need to ALLOWED_HOSTS variable in settings.py.
ALLOWED_HOSTS = ['your_domain.com','www.your_domain.com']
or, this will allow all the domain which is not recommended
ALLOWED_HOSTS = ['*']
I am also having the same issue however I am using the .env file to manage the settings.
settings.py # my settings file
DEBUG = env('DEBUG')
.env # my .env file
DEBUG=False
the app works exactly as intended except for for the debug part, by the way the app hosted on ubuntu 20.04

How to resolve recursion error in python django urls.py

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.

STATIC_ROOT in Django not working correctly

Trying to get static root set properly,
Went through the tango with Django tutorial and stuck on this part.
Basically this is my setting files, and the static folder is linked below in the tree.
C:.
├───media
│ └───locations
│ └───2018
│ └───11
│ └───11
│ └───20
│ └───18
├───Space
│ └───__pycache__
├───Spaces
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───static
│ ├───admin
│ │ ├───css
│ │ │ └───vendor
│ │ │ └───select2
│ │ ├───fonts
│ │ ├───img
│ │ │ └───gis
│ │ └───js
│ │ ├───admin
│ │ └───vendor
│ │ ├───jquery
│ │ ├───select2
│ │ │ └───i18n
│ │ └───xregexp
│ ├───css
│ └───images
│ └───parralax
│ └───home
├───templates
│ ├───registration
│ └───Spaces
└───users
├───migrations
│ └───__pycache__
└───__pycache__
and below you can see the settings i'm using for this .
"""
Django settings for Space project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5a#tkcbah13t_vb!6pp6#z1c3j-3abb!&$6r-mw+%0mtzg$qo#'
# 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',
'django.contrib.sites',
'users',
'Spaces',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
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 = 'Space.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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',
'django.template.context_processors.media'
],
},
},
]
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url
WSGI_APPLICATION = 'Space.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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/2.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',
},
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
AUTH_USER_MODEL = 'users.CustomUser'
SITE_ID = 1
LOGIN_REDIRECT_URL = 'home'
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
essentially just want the root for static to be where i've put "static" in the directory.
Essentially I'm uploading to Heroku ATM, and I'm getting an error that it can't find the static root.
When changing my STATIC_ROOT to,
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url
WSGI_APPLICATION = 'Space.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
I get this issue :(

Serve media on localhost (windows)

I have an img file which i copied to the /mediafiles/ folder. How can I display it? It just returns 404 (not found). Or is that not possible in DEBUG mode?
I've also tried using {{ MEDIA_URL }}img1.jpg in the template but to no avail.
FYI, I have no problems with static images or stylesheets (as long as I don't forget to run collectstatic).
Django 1.8.3, localhost on Windows, in a virtualenv.
Any ideas would be greatly appreciated.
myproject\myapp\settings.py:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS= (
os.path.join(BASE_DIR, 'static/myapp/theme_one'),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates/myapp/theme_one'),
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
myproject\myapp\urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^book/', 'book.views.protopage', name='protopage'),
)
myproject\book\views.py:
def protopage(request):
picurl = settings.MEDIA_URL + 'img1.jpg'
return render_to_response('book/protopage.html', locals(), context_instance=RequestContext(request))
myproject\book\templates\book\protopage.html:
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head><link href="{% static 'css/style.css'%}" rel="stylesheet"></head>
<body>
<img src='{{ picurl }}'/>
</body>
</html>
File structure
MYPROJECT
│ .gitignore
│ manage.py
├───book
│ views.py
├───myapp
│ settings.py
│ urls.py
├───mediafiles
│ img1.jpg
├───static
│ └───myapp
│ └───theme_one
│ ├───css
│ │ style.css
│ └───img
│ logo.png
├───staticfiles
├───templates
│ └───myapp
│ └───theme_one
│ └───book
│ └───protopage.html
└───venv
I got it to work after reading https://docs.djangoproject.com/en/1.8/ref/views/
In my urls.py file I need to add the static.serve() view:
from django.conf import settings
. . .
urlpatterns = patterns('',
url(r'^book/', 'book.views.protopage', name='protopage'),
(r'^mediafiles/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
}),
)