please can anyone help me i cant figure out what is the error while rendering template in djano 2.0
i created a app and and in the views.py section i added all thoe code lines of manange.py imported urls(directly in the views ) tried to run the server (python views.py runserver)
here is my complete code from views.py
import os
import sys
from django.conf import settings
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32))
ALLOWED_HOSTS = os.environ.get( 'localhost','127.0.0.1').split(',')
BASE_DIR = os.path.dirname(__file__)
settings.configure(
DEBUG=DEBUG,
SECRET_KEY=SECRET_KEY,
ALLOWED_HOSTS=ALLOWED_HOSTS,
ROOT_URLCONF=__name__,
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
)
INSTALLED_APPS=(
'django.contrib.staticfiles',
'django.contrib.contenttypes',
'django.contrib.auth',
),
TEMPLATE_DIRS=(
os.path.join(BASE_DIR, 'templates'),
),
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'static'),
),
STATIC_URL='/static/',
#############################views & urls###############################s
from django import forms
from django.urls import path,include
from django.core.cache import cache
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.http import etag
# Create your views here.
application = get_wsgi_application()
def home(request):
return render(request,'index.html')
urlpatterns=[
path('',home,name='home'),
]
###################################### #############################################
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
and i tried placing templates in the same directory where views exist and also in outside of the app folder
i should be getting a basic template as explained in the book lightweight django
instead:
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.0
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\madhumani\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\madhumani\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.2
Python Path:
['D:\\python\\tempo python\\dajngo rest api\\api\\pi',
'C:\\Users\\madhumani\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip',
'C:\\Users\\madhumani\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs',
'C:\\Users\\madhumani\\AppData\\Local\\Programs\\Python\\Python36-32\\lib',
'C:\\Users\\madhumani\\AppData\\Local\\Programs\\Python\\Python36-32',
'C:\\Users\\madhumani\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\madhumani\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages']
TEMPLATE_DIRS has not been a supported setting since Django 1.10. You should get a more up to date guide.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [os.path.join(BASE_DIR, 'templates')],
},
]
(Also, don't put your settings in your views. There's a settings.py file for a reason.)
Related
And here I am again.
I am trying to connect my app to MongoDB as I want to implement a non-rel database. The application works fine with SQL3Lite and I was also able to use Djongo. Yet, I am planning to use MongoEngine models and therefore I am trying to use it as DB Engine.
However, for whatever reason I receive an error settings.
"DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details."
Here is what I did:
django-admin startproject projectname
python manage.py startapp appname
Models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
from django.db.models.query import EmptyQuerySet
from django.contrib.auth.models import User,AbstractUser, UserManager
import datetime
import mongoengine
# Create your models here.
class Project(mongoengine.Document):
projectName = mongoengine.StringField()
Settings.py
import os
from pathlib import Path
import mongoengine
mongoengine.connect(db="testdatabase", host="mongodb+srv://<Username>:<Password>#cluster0.qspqt0a.mongodb.net/?retryWrites=true&w=majority")
# 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 = secretKey
# 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',
'rest_framework',
'api'
]
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 = 'prodash.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'prodash.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy'
}
}
At this point I receive always the same error if:
I create a superuser
I migrate data
I login into the app
(All of the above work with SQL3Lite)
My pip list is:
asgiref 3.5.2
certifi 2022.6.15
charset-normalizer 2.1.1
Django 4.1
djangorestframework 3.13.1
dnspython 2.2.1
idna 3.3
mongoengine 0.24.2
pip 22.2.2
pymongo 4.2.0
pytz 2022.2.1
requests 2.28.1
setuptools 63.4.3
sqlparse 0.4.2
urllib3 1.26.12
It might be a typo, but I can't figure out what I am doing wrong. Please, help.
I'm not able to import my views in the app folder to the URLS of project folder. I've tried every possible methods like 'from . import views' or 'from newapp import views as newapp_views' and 2-3 more alternatives that I searched on the internet. My app name is newapp and project name is newproject. Please help me.
This is my models file:
from django.db import models
class User(models.Model):
first_name=models.CharField(max_length=128)
last_name=models.CharField(max_length=128)
email=models.EmailField(max_length=256, unique=True)
This is my URLS of newapp folder:
from django.conf.urls import url
from django.urls.resolvers import URLPattern
from .models import views
urlpatterns= [url(r'^$', views.users, name='users'),
]
This is my views of newapp folder:
from django.shortcuts import render
from .models import User
def index(request):
return render(request, 'newapp/index.html')
def users(request):
user_list=User.objects.order_by('first_name')
user_dict={'users': user_list}
return render(request, 'newapp/users.html', context=user_dict)
This is my URLS of newproect folder:
from django.contrib import admin
from django.urls import path,include
from newapp import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls),
]
This is my settings file:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'newapp'
]
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',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
You can't import your file like this: from newapp import views.
And from . import views will work only if your urls.py file is in your app folder, while Django by default put it inside your project folder.
If you choose to have separated urls.py files per app (which is a good practice, as your project could grow into many apps), you could do the following:
newapp/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('users/',views.users, name="users"),
path('admin/', admin.site.urls)
]
newproject/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('newapp.urls'))
]
This way you just include the app urls in the project url file, and you can use a path to prefix all the app urls (instead of a blank string as above).
I am using python 3.4, django 1.8. I am using pycharm for developing. While running the program ,I am getting 'No module named 'django.templates'' error.
settings.py
"""
Django settings for dj project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uhqkhi7h_w48bz*gnr+_!roaa8#c_)087a(!ees)mn2=n=lv-r'
# 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',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'dj.urls'
TEMPLATES = [
{
'BACKEND': 'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
)
WSGI_APPLICATION = 'dj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
blog/urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
]
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
post_list.html
<html>
<body>
<p>
hihiiii
</p>
</body>
</html>
dj/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('blog.urls')),
]
Error
ImportError at /
No module named 'django.templates'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.1
Exception Type: ImportError
Exception Value:
No module named 'django.templates'
Exception Location: C:\Python34\lib\importlib\__init__.py in import_module, line 109
Python Executable: C:\Python34\python.exe
Python Version: 3.4.1
Python Path:
['C:\\Users\\ankur anand\\PycharmProjects\\dj',
'C:\\Users\\ankur anand\\PycharmProjects\\dj',
'C:\\Windows\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Fri, 15 May 2015 18:08:59 +0530
This can happen if you are not familiar with Pycharm IDE refactoring.
You renamed the "templates" directory to another name by refactoring.
When you do this, Pycharm also renames some strings in "settings.py".
Solution: Right click your "setting.py":
LocalHistory -> ShowHistory then restore you "setting.py".
Use this and replace it existing values. As in last post he told you that you just needed to remove "s" from relevant fields. But if you couldn't understand it then just copy paste.
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',
],
},
},
]
As the error mentions, there's no such thing as django.templates.
However, there is a django.template. You'll want to remove the s from all of the relevant lines that refer to templates.
While you're at it, you should also move your TEMPLATE_LOADERS to their proper location (within the TEMPLATES setting).
Read more in the docs.
I got the same exception with you when start my first django project...
i think maybe you changed the template dir name from 'template' to 'templates' in pycharm ,but didn't aware that pycharm changed the TEMPLATES.context_processors configs in setting.py at the sametime. it changed
django.template.context_processors.debug
django.template.context_processors.request
to
django.templates.context_processors.debug
django.templates.context_processors.request
.it's the cause of the problem.
This did happened due to Refactoring in Pycharm. I faced the same issue initially, when changed the directory name "template" to "templates".
To resolve this: Right click settings.py > local history > show history > revert.
It reverted the changes made in the settings file due to refactoring but kept the directory name to "Templates". Hence, resolving the issue.
in settings.py templates list is having key name DIRS that is empty, it should not be 'DIRS':[], RIGHT WAY -> add that value 'DIRS':[BASE_DIR / 'templates'] in settings.py
True, it is related to refactoring directory name from template to templates in my case.Need to correct change settings.py file under TEMPLATES(for me error was no module found "django.template" )
changes to be made under TEMPLATES is remove "s" from
django.templates.context_processors.debug
django.templates.context_processors.request
to:
django.template.context_processors.debug
django.template.context_processors.request
I am trying to upload file in /media/ folder in my django project name codewar.Here I am creating a independent folder for each user and placing the uploaded files in it. However my files are not being uploaded and I am getting error after submitting the query as
TypeError at /index/
an integer is required
Request Method: POST
Request URL: http://127.0.0.1:8000/index/
Django Version: 1.7
Exception Type: TypeError
Exception Value:
an integer is required
Exception Location: C:\Python27\codewar\codewar\views.py in cust_proc, line 38
Python Executable: C:\Python27\python.exe
Python Version: 2.7.5
Python Path:
['C:\\Python27\\codewar',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages']
Server time: Mon, 16 Feb 2015 17:29:28 +0530
my urls.py is
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from codewar.views import *
from django.conf import settings
urlpatterns = patterns('',(r'^index/$',mainsite),url(r'^admin/', include(admin.site.urls))) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('',) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my views.py is
from django.shortcuts import *
from django.http import *
from django.template.loader import *
from django.template import *
from os import *
from os.path import *
from django.template import RequestContext
from django.conf import settings
def mainsite(request):
if request.method=='POST':
return render_to_response('index.html',context_instance=RequestContext(request,processors=[cust_proc]))
else:
return render_to_response('index.html',context_instance=RequestContext(request))
def cust_proc(request):
data={}
if request.method == 'POST':
newpath="C:\\Python27\\codewar\\media\\"+request.POST.get('name')
if not exists(newpath):
mkdir(newpath)
#t=save_file(request.POST.get('name'),request.FILES.get('browse'))
if 'file' in request.FILES:
file = request.FILES['file']
print file
# Other data on the request.FILES dictionary:
# filesize = len(file['content'])
# filetype = file['content-type']
dirname=request.POST.get('name')
filename = request.POST.get('filename')#file['filename']
s= settings.MEDIA_ROOT+"\\"+dirname+"\\"+filename
print s
#fd = open('%s' % (s), 'wb')
fd=request.FILES['file'].read()
fdd=open(s,"w")
ffd.write(fd)
fdd.close()
#fd.write(file['content'])
data={
'name':request.POST.get('name'),
'filename':request.POST.get('filename'),
'code':request.FILES['file'].read()
}
return {'data':data}
my settings.py is:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'codewar.urls'
WSGI_APPLICATION = 'codewar.wsgi.application'
STATIC_URL = '/static/'
STATIC_ROOT = "C:\Python27\codewar\static"
TEMPLATE_DIRS=(
'C:\Python27\codewar',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATICFILES_DIRS = (
'C:\Python27\codewar\staticfiles',
)
MEDIA_ROOT = 'C:\Python27\codewar\media'
MEDIA_URL = '/media/'
I think line 38 is this line:
fdd=open(s,"w")
Note that you are importing os.open using this statement in the beginning of your views.py:
from os import *
In line 38 you are actually trying to call os.open. Now, os.open (docs) is different than built-in open (docs). It expects an integer mode argument.
You should modify your import line to import only necessary functions from os library.
As a side note, wildcard imports are not advised because of namespace pollution causing errors of this kind.
I've just set up a django project and got an error:
Request Method: GET
Request URL: http://127.0.0.1/hello/
Django Version: 1.6.6
Exception Type: ImproperlyConfigured
Exception Value:
The included urlconf <function hello at 0x7f665a1e0320> doesn't have any patterns in it
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in url_patterns, line 369
Python Executable: /usr/local/bin/uwsgi
Python Version: 2.7.6
urls.py:
from django.conf.urls import patterns, include, url
import testsite.views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/', include(testsite.views.hello)),
)
views.py:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, world!")
settings.py:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production sexbbiv*#q44x+jdawuchyu_!$wd#f-p(hid2r*zrjvy6a6#bsoxbbiv*#q44x+jdawuchyu_!$wd#f-p(hid2r*zrjvy6a6#bsocret!
SECRET_KEY = '##############&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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_CLASSES = (
'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 = 'testsite.urls'
WSGI_APPLICATION = 'testsite.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
I've googled about setting DEBUG_TOOLBAR_PATCH_SETTINGS = False but it didnt help. What's the problem and how to fix it?
The error is clear: it's not a valid url configuration.
To correct the problem, you can do it like this:
# app/views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, world!")
Now create a file in that app called urls.py:
# app/urls.py
from django.conf.urls import url
from app import views
urlpatterns = [
url(r'^$', views.hello, name='hello'),
]
And now finally in site/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^hello/', include('app.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Do not use include() for a view pattern:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/', testsite.views.hello),
)
include() is for "including" url configuration in-place from another module/application.