KeyError at /app/myRoute/ 'Status' - AJAX Post Django - python

From my view, I am simply returning
context = {'message':'Request Accepted'}
return HttpResponse(context)
I am calling this view with AJAX call and its returning Http 500
with error message
KeyError at /routes/AcceptRequest/
'status'
Request Method: POST
when i try to stringify the response in javascript it gives :
{"readyState":4,"responseText":"KeyError at /routes/AcceptRequest/\n'status'\n\nRequest Method: POST\nRequest URL: http://localhost:8000/routes/AcceptRequest/\nDjango Version: 1.4\nPython Executable: /home/subodh/joinwheelsv6/env/bin/python\nPython Version: 2.7.3\nPython Path: ['/home/subodh/joinwheelsv6/env/joinwheels', '/home/subodh/joinwheelsv6/env/lib/python2.7/site-packages/PIL-1.1.7-py2.7-linux-x86_64.egg', '/home/subodh/joinwheelsv6/env/lib/python2.7', '/home/subodh/joinwheelsv6/env/lib/python2.7/plat-linux2', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-tk', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-old', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages', '/home/subodh/joinwheelsv6/env/lib/python2.7/site-packages']\nServer time: Thu, 17 Oct 2013 15:48:36 +0530\nInstalled Applications:\n('django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n 'south',\n 'account',\n 'socialaccounts',\n 'routes',\n 'Groups')\nInstalled Middleware:\n('django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware')\n\nTraceback:\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/core/handlers/base.py\" in get_response\n 111. response = callback(request, *callback_args, **callback_kwargs)\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/views/generic/base.py\" in view\n 48. return self.dispatch(request, *args, **kwargs)\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/views/generic/base.py\" in dispatch\n 69. return handler(request, *args, **kwargs)\nFile \"/home/subodh/joinwheelsv6/env/joinwheels/routes/views.py\" in post\n 1157. return HttpResponse(response['Status'])\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/http/__init__.py\" in __getitem__\n 615. return self._headers[header.lower()][1]\n\nException Type: KeyError at /routes/AcceptRequest/\nException Value: 'status'\nRequest information:\nGET: No GET data\n\nPOST:\ncsrfmiddlewaretoken = u'Dxm5R7omqawuGtJ2v8AuOGsDXXdTCXCa'\nRequestID = u'7'\n\nFILES: No FILES data\n\nCOOKIES:\ncsrftoken = 'Dxm5R7omqawuGtJ2v8AuOGsDXXdTCXCa'\nsessionid = '139167c44021568cf40311753e0480fc'\n\nMETA:\nwsgi.version = \nwsgi.multiprocess = False\nRUN_MAIN = 'true'\nHTTP_REFERER = 'http://localhost:8000/account/TravelCard/Ride/2059/7/'\nGNOME_DESKTOP_SESSION_ID = 'this-is-deprecated'\nSERVER_PROTOCOL = 'HTTP/1.1'\nSERVER_SOFTWARE = 'WSGIServer/0.1 Python/2.7.3'\nSCRIPT_NAME = u''\nLESSOPEN = '| /usr/bin/lesspipe %s'\nREQUEST_METHOD = 'POST'\nLOGNAME = 'subodh'\nUSER = 'subodh'\nHTTP_ORIGIN = 'http://localhost:8000'\nPATH = '/home/subodh/joinwheelsv6/env/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'\nQUERY_STRING = ''\nGNOME_KEYRING_CONTROL = '/tmp/keyring-KIXbNa'\nPS1 = '(env)\\\\[\\\\e]0;\\\\u#\\\\h: \\\\w\\\\a\\\\]${debian_chroot:+($debian_chroot)}\\\\u#\\\\h:\\\\w\\\\$ '\nDISPLAY = ':0'\nSSH_AGENT_PID = '2016'\nLANG = 'en_IN'\nTERM = 'xterm'\nSHELL = '/bin/bash'\nXDG_SESSION_PATH = '/org/freedesktop/DisplayManager/Session0'\nXAUTHORITY = '/home/subodh/.Xauthority'\nLANGUAGE = 'en_IN:en'\nSESSION_MANAGER = 'local/dell:#/tmp/.ICE-unix/1981,unix/dell:/tmp/.ICE-unix/1981'\nSHLVL = '1'\nMANDATORY_PATH = '/usr/share/gconf/ubuntu.mandatory.path'\nwsgi.url_scheme = 'http'\nCOMPIZ_CONFIG_PROFILE = ...

Well, you seem to be doing something else that you haven't explained. From your error, cleaned up slightly:
File "/home/subodh/joinwheelsv6/env/joinwheels/routes/views.py" in post
1157. return HttpResponse(response['Status'])
So you have some code in views.py that is looking for a Status field that doesn't exist. Of course, we have no idea why.

Change the return line:
import json
return HttpResponse(json.dumps(context))

Related

Django Python Error: 'dict' object has no attribute 'status_code'

I'm getting the following error after a post:
'dict' object has no attribute 'status_code'
I'm using django 3.1.7 and python 3.8.
Can anyone help me with this problem? I'm new to this stuff and can't seem to solve it alone.
the .py:
from gluon import *
from .models import *
from lxml import etree as ET
import re
import requests
def update_customer(request, p_externalcode, p_addressexternalcode, p_street, p_nr, p_addition, p_zipcode, p_city, p_country, p_complexnr, p_region, p_company_code, controle, omgeving):
url = request.session['omgeving_url']+'/mds/soapservice/outbound.asmx'
lic = '{'+request.session['omgeving_lic']+'}'
gebruiker = request.session['omgeving_geb']
wachtwoord = request.session['omgeving_pas']
omgnaam = request.session['omgeving_naam']
headers = {'content-type':'text/xml', 'charset':'utf-8'}
# opbouw van de SOAP-xml
SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
PCA_NS = 'http://www.pcamobile.com/mds'
ns_map = {'SOAP': SOAP_NS}
pca_map = {None: PCA_NS}
envelope = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
body = ET.SubElement(envelope, ET.QName(SOAP_NS, 'Body'), nsmap=ns_map)
rqoutboundmessage = ET.SubElement(body, ET.QName(PCA_NS,'RqOutboundMessage'), nsmap=pca_map)
header = ET.SubElement(rqoutboundmessage, 'Header')
version = ET.SubElement(header, 'Version')
companyid = ET.SubElement(header,'CompanyID')
messageid = ET.SubElement(header,'MessageID')
messagetype = ET.SubElement(header,'MessageType')
testmessage = ET.SubElement(header,'TestMessage')
rqdefinition = ET.SubElement(rqoutboundmessage,'RqCustomerDefinition')
nodes = ET.SubElement(rqdefinition,'Customers')
updated = ET.SubElement(nodes,'Updated')
node = ET.SubElement(updated,'Customer')
externalcode = ET.SubElement(node,'ExternalCode')
if str(p_addressexternalcode or '') != '':
if p_addressexternalcode[:10] == 'AholdStore':
name = ET.SubElement(node,'Name')
name.text = p_addressexternalcode[-4:]
address = ET.SubElement(node,'Address')
if str(p_addressexternalcode or '') != '':
addrexternalcode = ET.SubElement(address,'ExternalCode')
addrexternalcode.text = re.sub('[^ \-\.0-9#A-Z_a-z]+', '', p_addressexternalcode)
street = ET.SubElement(address,'Street')
nr = ET.SubElement(address,'Nr')
if str(p_addition or '') != '':
nraddition = ET.SubElement(address,'NrAddition')
nraddition.text = p_addition
zipcode = ET.SubElement(address,'ZipCode')
city = ET.SubElement(address,'City')
country = ET.SubElement(address,'Country')
countrycode = ET.SubElement(country,'ExternalCode')
if str(p_complexnr or '') != '':
complexname = ET.SubElement(address,'ComplexName')
complexname.text = p_complexnr
region = ET.SubElement(node,'Region')
regexternalcode = ET.SubElement(region,'ExternalCode')
companycode = ET.SubElement(node,'CompanyID')
#vulling van de SOAP-xml
companyid.text = lic
version.text = '1.0'
messageid.text = '{00009000-0000-0000-0000-000000000000}'
messagetype.text = 'RqCustomerDefinition'
testmessage.text = str(controle)
externalcode.text = re.sub('[^.0-9#A-Z_a-z]+', '', p_externalcode)
street.text = p_street
nr.text = str(p_nr)
zipcode.text = p_zipcode
city.text = p_city
countrycode.text = p_country
regexternalcode.text= p_region
companycode.text = p_company_code
# maak er een tekstfile van.
body = ET.tostring(envelope, pretty_print=True)
response = requests.post(url,data=body,headers=headers, auth=(gebruiker, wachtwoord))
root = ET.fromstring(response.text.encode('ascii','ignore'))
if response.status_code == 200:
status = 0
else:
status = 1
Verwerking.objects.create(omgeving=omgnaam, Status=status, bericht=body, antwoord=ET.tostring(root, pretty_print=True).decode())
return status
Terminal Response:
[21/Mar/2021 16:25:49] "GET /woningbeheer HTTP/1.1" 200 58463
[21/Mar/2021 16:25:50] "GET /static/js/main.js HTTP/1.1" 304 0
[21/Mar/2021 16:25:50] "GET /woningbeheer HTTP/1.1" 200 58468
Internal Server Error: /woningbeheer/syncPCAind/5897
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response
if response.status_code == 404:
AttributeError: 'dict' object has no attribute 'status_code'
[21/Mar/2021 16:25:53] "GET /woningbeheer/syncPCAind/5897 HTTP/1.1" 500 65689
Internal Server Error: /woningbeheer/syncPCAind/9640
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python38\lib\site-packages\django\utils\deprecation.py", line 116, in __call__
response = self.process_response(request, response)
File "C:\Python38\lib\site-packages\django\middleware\common.py", line 106, in process_response
if response.status_code == 404:
AttributeError: 'dict' object has no attribute 'status_code'
[21/Mar/2021 16:39:41] "GET /woningbeheer/syncPCAind/9640 HTTP/1.1" 500 65689
Maybe useful:
AttributeError at /woningbeheer/syncPCAind/82689
'dict' object has no attribute 'status_code'
Request Method: GET
Request URL: http://127.0.0.1:8000/woningbeheer/syncPCAind/82689
Django Version: 3.1.7
Exception Type: AttributeError
Exception Value:
'dict' object has no attribute 'status_code'
Exception Location: C:\Python38\lib\site-packages\django\middleware\common.py, line 106, in process_response
Python Executable: C:\Python38\python.exe
Python Version: 3.8.8
Python Path:
['C:\\Users\\wgeboers\\OneDrive - Coen Hagedoorn Bouwgroep '
'B.V\\Django-Docker\\databeheer',
'C:\\Python38\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Python38\\lib\\site-packages']
Server time: Sun, 21 Mar 2021 15:44:25 +0000
Thanks in advance and if there is more information needed let me know.

Perform google search then get result save in django database

i am learning Django tutorial, could you pls advise me how to edit cod to get search result to put into database? Below are my cod and sure that the rest of cod in this tutorial i did correctly and test complete, many thanks
I have updated the code as per your request. The result on home page fail is also attached at the bottom of the question section. If you have any additional question, please ask and I will be able to share.
def __str__(self):
"""Returns a string representation of a message."""
date = timezone.localtime(self.log_date)
return f"'{self.message}' logged on {date.strftime('%A, %d %B, %Y at %X')}"
class HomeListView(ListView):
"""Renders the home page, with a list of all messages."""
model = LogMessage
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
return context
def log_message(request):
form = LogMessageForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
query = form.save(commit=False)
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0):
message = LogMessage(log_date = datetime.now(), message =j)
message.save()
return redirect("home")
else:
return render(request, "hello/log_message.html", {"form": form})
--- HOME PAGE FAIL INFO
TypeError at /log/
quote_from_bytes() expected bytes
Request Method: POST
Request URL: http://127.0.0.1:8000/log/
Django Version: 3.1.5
Exception Type: TypeError
Exception Value:
quote_from_bytes() expected bytes
Exception Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py, line 866, in quote_from_bytes
Python Executable: C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\python.exe
Python Version: 3.8.7
Python Path:
['D:\\Apps\\07.1\\hello_django',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
Server time: Thu, 07 Jan 2021 14:38:11 +0000
Traceback Switch to copy-and-paste view
C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
D:\Apps\07.1\hello_django\hello\views.py, line 34, in log_message
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0): …
▼ Local vars
Variable Value
form
<LogMessageForm bound=True, valid=True, fields=(message)>
query
<LogMessage: '333321212121121221' logged on Thursday, 07 January, 2021 at 14:38:11>
request
<WSGIRequest: POST '/log/'>
Try the code below:
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0):
message = LogMessage(log_date = datetime.now(), message =j)
message.save()

'str' object has no attribute 'GET' when requesting to django script

i have been working with django to make an interactive web page. But when i try to make a Http request to a django view. It throws that error, even though i have the exact same code above and that works just fine. Here is my Python code:
def test(request):
default = {"Error" : "Could not make request"}
name = request.GET.get('showname')
token = getToken()
showJs = searchShowId(name, token)
if showJs.get('Error'):
try:
token = refreshToken(token)
showJs = searchShowId(name, token)
return JsonResponse(showJs)
except KeyError as error:
token = login()
showJs = searchShowId(name, token)
return JsonResponse(showJs)
else:
return JsonResponse(showJs)
def image(request):
default = {"Error" : "Could not make request"}
id = request.GET.get('id')
return JsonResponse(image(id))
this is the full error:
Traceback:
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image
33. return JsonResponse(image(id))
File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image
32. id = request.GET.get('id')
Exception Type: AttributeError at /image/
Exception Value: 'str' object has no attribute 'GET'
Javascript Code:
function search() {
console.log('Function Called')
var showName = document.getElementById('showName');
console.log(showName.value);
var name = stringToPost(showName.value);
$.ajax({
type: "GET",
url: "/request/",
data: {
showname: showName.value
},
success: function (dato) {
dato = dato['data'];
for (var i = 0; i < dato.length; i++) {
$.ajax({
type: "GET",
url: "/image/",
data: {
id : dato[i]['id']
},
success: function (datax) {
console.log(datax);
},
});
}
},
});
Like i already said, the test function works perfectly, but the image one doesnt. What could it be?
That's because in your image function, you return image(id) which calls the same function, but this time with id instead of a request object.
Try naming the 2 things differently, e.g. you can rename the view function to image_view.

Django celery task_id is null

I'm trying to implement a progress bar in Django, I'm taking references from this code snippet I found http://djangosnippets.org/snippets/2898/ but my efforts are in vane because I don't know what happening but the task_idfor celery is always null when executes the method task, that's my code:
def add_categoria(request):
if request.POST:
form_cat = CategoriaModelForm(request.POST,request.FILES)
if form_cat.is_valid():
file = request.FILES['imagen']
job = upload_image_categoria(request).delay()
request.session['task_id'] = job.id
return HttpResponse(json.dumps({'task_id':job.id}))
else:
return HttpResponseBadRequest(json.dumps(form_cat.errors),
mimetype="application/json")
else:
form = CategoriaModelForm()
return render_to_response("ventas/form.html",{'form':form},context_instance=RequestContext(request))
#task()
def upload_image_categoria(request):
form = CategoriaModelForm(request.POST, request.FILES)
path = MEDIA_ROOT+'/categorias/%s' % form.cleaned_data['imagen'].name
file = request.FILES['imagen']
destination = open(path, 'wb+')
porcentaje = 0
acum = 0
for chunk in file.chunks():
time.sleep(0.1)
current_task.update_state(state='PROGRESS', meta={'current': porcentaje})
acum += len(chunk)
porcentaje = int((acum*100)/file.size)
destination.write(chunk)
#csrf_exempt
def upload_state(request):
""" A view to report the progress to the user """
data = 'Fail'
if request.is_ajax():
if 'task_id' in request.POST.keys() and request.POST['task_id']:
task_id = request.POST['task_id']
task = AsyncResult(task_id)
data = task.result or task.state
else:
data = 'No task id'
else:
data = 'This is not an ajax request'
json_data = json.dumps(data)
return HttpResponse(json_data, mimetype='application/json')
So, when I report the state of progress bar in upload_image_categoria at current_task.update_state(state='PROGRESS', meta={'current': porcentaje}) always I get this Traceback:
Traceback:
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in add_categoria
446. job = upload_image_categoria(request).delay()
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in __call__
330. return self.run(*args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in upload_image_categoria
462. current_task.update_state(state='PROGRESS',meta={'current': i, 'total': 100})
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in update_state
695. self.backend.store_result(task_id, meta, state)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/base.py" in store_result
282. self._store_result(task_id, result, status, traceback, **kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/amqp.py" in _store_result
128. routing_key=task_id.replace('-', ''),
Exception Type: AttributeError at /ventas/categorias/add/
Exception Value: 'NoneType' object has no attribute 'replace'
That's my settings.py for celery options:
BROKER_URL = "amqp://guest#localhost:5672//"
CELERY_IMPORTS = ("ventas.forms",)
CELERY_TRACK_STARTED = True
CELERY_RESULT_BACKEND = "amqp"
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_RESULT_DBURI = "mysql://root#localhost/dgp"
So I don't know what's happening, worker is correctly, settings (I guess, is correctly) and always I get the same, I prove in some other projects with the same settings (this project particularly http://iambusychangingtheworld.blogspot.com.es/2013/07/django-celery-display-progress-bar-of.html) and it works perfectly so I don't know why here not, something I'm missing? Any ideas would be appreciate.
Regards!

'str' object has no attribute 'csrf_exempt' while returning response from a django view?

I have this strange problem with my view which is returning response in json format.My view looks like this:
def CheckPlayer(request,client_id):
if request.method == 'GET':
try:
user = User.objects.get(id = client_id)
except:
return Error(message = "User doesnot exists.")
message = request.GET.get('message','')
if not message:
return Error(message = "Argument Missing.")
response = {}
result = MakingRequest(message)
result = json.loads(result)
if result['failure'] == '0':
response['failure'] = '0'
else:
response['failure'] = '1'
return HttpResponse(json.dumps(response), mimetype="application/javascript")
else:
return Error()
def MakingRequest(message):
values = {'message':message}
rObjects = Ram.objects.all()
temp = []
for i in rObjects:
temp.append(i.appId)
values['registration_ids'] = temp
param = json.dumps(values)
req = urllib2.Request("https://android.googleapis.com/gcm/send", param)
req.add_header( 'Content-Type' , 'application/json' )
req.add_header( 'Authorization' , 'key=7FcEMnl0FRTSBjhfjfhjfHi1Rmg04Ns' )
response = urllib2.urlopen(req)
return response.read()
I have tested it on my local server it works perfectly , but if I run it on my server (nginx,gunicorn,django-mongoDB,mongoDB) then it gives me this Error.I know about this error that if a view doesnot return HttpResponse from a view then it djangi raises error "Nonetype object has no attribute csrf_exempt' " but in my case i am returning response which is in json format but still its giving me error.Please help me
You aren't returning an HttpResponse when you return Error(), so Django can't apply the decorator to it.

Categories