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.
Related
I'm making use of Django haystack for my blog with solr as my search engine. I have also setup my solr(version 6.6.6) properly and all query are showing on the solr website. But when I make use of the SearchQuerySet
it returnss none upon query. I have included code below.
views.py
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views import generic
from blog.views import Post
from django.views.generic.base import TemplateView
from haystack.query import SearchQuerySet
import logging
logger = logging.getLogger(__name__)
class Search(TemplateView):
template_name = 'blog/post_search.html'
def get(self, request, **kwargs):
query = request.GET.get('query', '')
results = SearchQuerySet().models(Post).filter(content='query').load_all()
total = results.count()
return render(request, self.template_name, {'results':results, 'total':total})
search_indexes.py
from haystack import indexes
from blog.models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
publish = indexes.DateTimeField(model_attr='publish_date')
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.published()
settings.py
"""
Django settings for radd project.
Generated by 'django-admin startproject' using Django 3.0.5.
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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
SITE_ID = 1
ALLOWED_HOSTS = ['www.rad.com', '127.0.0.1', 'rad.com', 'localhost', '192.168.43.195']
# 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',
'django_comments',
'django_comments_xtd',
'rest_framework',
'blog',
'mptt',
'haystack',
# third party apps
'crispy_forms',
]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr/blog',
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
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.)
I have a strange behavior when I try to test my Django on the webpage.
I see what is the error, but I have no clue from where it comes.
What I try to do is :
I have project called stockmarket
I have application called stockanalysis
the problem is :
when I try to open 'domain/stockmarket I get this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8888//
When I try to open 'domain/stockmarket/stockanalysis'
I get this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8888//stockanalysis/
The issue is clear to me. In both cases I have two slashes (//) instead of one (/).
The issue is - I do not know from where it comes.
Any ideas?
here some files:
urls.py (project folder)
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^stockanalysis/', include('stockanalysis.urls')),
url(r'^admin/', admin.site.urls),
]
urls.py (app. folder)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
views.py (app folder)
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the index.")
setting.py (project folder)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '****************************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'stockanalysis.apps.StockanalysisConfig',
'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 = 'stockmarket.urls'
WSGI_APPLICATION = 'stockmarket.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
Issue is solved.
As I expected nothing wrong was with the files itself (like urls.py or settings.py).
The company which hosts the files did a mistake in vhosts entries in Apache. That's what they told me.
After I created my first Django project I was asked to provide some details, so they could do some adjustments on server side. While doing this they did mistake.
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.
I'm using django-nonrel on google app engine.
I've got this problem when visiting http://localhost:8080/album
Could not import myapp.views. Error was: No module named myapp.views
my urls:
urlpatterns = patterns('',
('^_ah/warmup$', 'djangoappengine.views.warmup'),
('^$', 'django.views.generic.simple.direct_to_template', {'template': 'home.html'}),
(r'^album/$', 'myapp.views.view_albums'),
(r'^admin/', include(admin.site.urls)),
)
my views:
def view_albums(request):
return direct_to_template(request, 'album.html', locals())
Part of Settings:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
# 'django.contrib.sites',
'djangotoolbox',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
PROJECT_DIR = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media/')
ADMIN_MEDIA_PREFIX = '/media/admin/'
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
ROOT_URLCONF = 'urls'
I'm not using django's site framework, the app structure is
myapp
-\dbindexer
-\django
-\djangoappengine
-\djangotoolbox
-\media
-\templates
-__init__.py
-app.yaml
-views.py
-urls.py
-settings.py
-models.py
-manage.py
-cron.yaml
-dbindexes.py
...
I think you are using
from myapp.views import * in urlconf
please try
-- in urlconf
from views import *