I am trying to read the file content using URL and return that the content as response in html format but getting the following error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/lampp/htdocs/rework/Nuclear/RFI/secure/plant/views.py", line 217, in view_reactor
pers = User.objects.get(pk=request.session['id'])
File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
return self._session[key]
KeyError: u'id'
I am providing my code below:
site = 'http://127.0.0.1:8000/'
my_list = []
my_list.extend(['home', 'view_reactor'])
if request.GET.get('file') is not None and request.GET.get('file') != '':
file = request.GET.get('file')
if file in my_list:
full_path = site+file
response = urllib.urlopen(full_path)
lines = response.readlines()
return HttpResponse(content=lines, content_type="text/html")
else:
return render(request, 'plant/home.html', {'count': 1})
else:
return render(request, 'plant/home.html', {'count': 1})
def view_reactor(request):
""" This function for to get serch screen. """
pers = User.objects.get(pk=request.session['id'])
root = []
user_name = pers.uname
count = 1
root.append(
{'username': user_name,
'count': count
})
return render(request, 'plant/view_reactor.html',
{'user': root, 'count': 1})
Here I am passing the the value in query string like this http://127.0.0.1:8000/createfile/?file=view_reactor and finally I need the response of http://127.0.0.1:8000/view_reactor page in html format. But in my code I am getting this error.
The error is saying that there is no id key in your session dictionary. In the following line:
pers = User.objects.get(pk=request.session['id'])
And to me it looks redundant to get a user like this. You should be able to get a user simply by doing this:
pers = request.user
Provided that you have auth middleware installed.
Second option (not tested though):
pers = User.objects.get(pk=request.session['_auth_user_id'])
Related
I am getting a JSON Decode error at /charge when data = json.loads(request.body).
I am working with stripe api as well as fetch api.
The full error is this:
Traceback (most recent call last):
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/antariksh/Desktop/Python Files/Owlet/Menu/views.py", line 151, in charge
data = json.loads(request.body)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
That is the error. My code for the /charge/ view is this:
#csrf_exempt
def charge(request):
if request.method == 'POST':
print(request.POST)
transaction_id = uuid.uuid4().hex
data = json.loads(request.body)
print(data)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, isComplete=False, status='Created')
else:
order, customer = guestOrder(request, data)
total = data['form']['total']
order.transaction_id = transaction_id
order.isComplete = True
order.status = 'Accepted'
order.save()
ShippingAddress.objects.create(
customer = customer,
order = order,
address = data['shipping']['address'],
city = data['shipping']['city'],
state = data['shipping']['state'],
zipcode = data['shipping']['zipcode'],
)
mailOrder(data['form']['email'], order)
return redirect(reverse('menupage'))
The JSON is fine since I checked everything which is parsed and when I ran the code. It saves the data in the database but still shows the error page. The javascript is this:
var url = '/charge/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken': csrftoken
},
body:JSON.stringify({'form':userData, 'shipping':shippingData}),
})
.then((response) => {
response.json()
})
.then((data) => {
console.log(data)
swal({
icon: "success",
text: "Transaction Completed"
});
cart = {}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
});
The above javascript is fine in terms of syntax. If there is some problem in JSON or anything please help. Help is much appreciated. Please look and tell me what is wrong. Any advice is also much appreciated. I haven't shared the stripe API code.
I'm trying to process many json files with user input.
If there are three indentical data ["a","a","a"] in GeneListA, I suppose it is going to run the code three times with
jsonurl = "http://abc.def/a/format=json"
However, I got the error :
Traceback (most recent call last):
File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/me/miniconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/me/Desktop/Project/gsea/analysis/views.py", line 49, in result
for gene in data[0][gidA]:
KeyError: 'NC_000913\r\nNC_000913\r\nNC_000913'
And here is my code:
AGOAnnos = []
for genefromlist in GeneListA:
jsonurl = "http://abc.def/"+genefromlist+"/format=json"
print(jsonurl)
with urllib.request.urlopen(jsonurl) as url:
data = json.loads(url.read().decode())
for gene in data[0][gidA]:
for anno in data[0][gidA][gene]:
if type(anno) is dict:
GOAnno = re.search(r'GO:\d+',anno["ID"])
if GOAnno:
AGOAnnos.append(GOAnno.group())
elif type(anno) is str:
GOAnno = re.search(r'GO:\d+',anno)
if GOAnno:
AGOAnnos.append(GOAnno.group())
I can't find what are the values of variables (gidA / gene) in your code.
The error raised because the in the data response there is no key with gidA
I am implementing a Django app, I am trying to fetch data from an LDAP server.
Here is my code in views.py.I have supplied all the necessary information below, but yet I am facing (2, 'No such file or directory') error. What Am I missing here?
LDAP_USERNAME = ""
LDAP_PASSWORD = ""
LDAP_BASEDN = ""
try:
l = ldap.initialize('')
l.protocol_version = ldap.VERSION2
l.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
search_filter = "(cn=*)"
search_attribute = None
search_scope = ldap.SCOPE_SUBTREE
ldap_result_id = l.search(LDAP_BASEDN, search_scope, search_filter, search_attribute)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
print result_set
except ldap.LDAPError, e:
print e
Error Traceback:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/////views.py", line 43, in index
l = ldap.initialize('xyz')
File "/Library/Python/2.7/site-packages/ldap/functions.py", line 94, in initialize
return LDAPObject(uri,trace_level,trace_file,trace_stack_limit)
File "/Library/Python/2.7/site-packages/ldap/ldapobject.py", line 79, in __init__
self._l = ldap.functions._ldap_function_call(ldap._ldap_module_lock,_ldap.initialize,uri)
File "/Library/Python/2.7/site-packages/ldap/functions.py", line 66, in _ldap_function_call
result = func(*args,**kwargs)
LDAPError: (2, 'No such file or directory')
ldap.initialize() requires a proper URL for the LDAP source. I had a same issue and LDAPError: (0, 'Error') and LDAPError: (2, 'No such file or directory') with flask helped me.
Try ldap.initialize(<protocol>://<host>:<port>). default protocol would be ldap and the default port is 389.
I'm having an issue building a list of dictionaries like this
#login_required(login_url="login/")
def home(request):
user = StaticHelpers.user_to_subclass(request.user)[1]
user_type = StaticHelpers.user_to_subclass(request.user)[0]
if user_type == "Patient":
apps = StaticHelpers.find_appointments(user)
events = []
for app in apps:
events.append({
'title': str(app.doctor),
'start': str(app.start_time),
'end': str(app.end_time)
})
return render(request, 'HealthApp/patientIndex.html', events)
elif user_type == "Doctor" or user_type == "Nurse":
return render(request, 'HealthApp/doctorIndex.html')
elif user_type == "Admin":
return render(request, 'HealthApp/doctorIndex.html')
Each dictionary needs to have those 3 values, and I need a list of them. However it just spits out this error at me
Internal Server Error: /
Traceback (most recent call last):
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/devin-matte/Documents/Healthnet/trunk/HealthApp/views.py", line 23, in home
return render(request, 'HealthApp/patientIndex.html', events)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/loader.py", line 97, in render_to_string
return template.render(context, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/backends/django.py", line 92, in render
context = make_context(context, request)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 291, in make_context
context.push(original_context)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 61, in push
return ContextDict(self, *dicts, **kwargs)
File "/home/devin-matte/.local/lib/python3.5/site-packages/django/template/context.py", line 20, in __init__
super(ContextDict, self).__init__(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
[05/Mar/2017 19:56:17] "GET / HTTP/1.1" 500 99419
The traceback shows that the problem is nothing to do with creating the dictionaries, but in how you send them to the template. The third argument to render must be a dict, where the keys are the name you want to use to refer to that value in the template. So:
return render(request, 'HealthApp/patientIndex.html', {"events": events})
Now you can iterate through events in the template.
I want to write a testcase for sending post data to login page. It does not work. I post my code here and wish you can help me. Thanks.
def setUp(self):
"""set up"""
un = 'abc#gmail.com'
pw = '123'
self.user = User.objects.create_user(un, un)
self.user.is_staff = True
self.user.is_superuser = True
self.user.firstname = "John"
self.user.lastname = "Smith"
self.user.password = '123'
self.user.save()
print '*** password: ', self.user.password
def testPost(self):
"""test POST requests"""
post_data = {
'email': 'abc#gmail.com',
'password': '123',
}
response = self.client.post(reverse('myapp_home', post_data))
print response.status_code
The error output is at below.
ERROR: testPost (submngr.tests.model_tests.model_tests.FormsTestCase)
test POST requests
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/model_tests/model_tests.py", line 117, in testPost
response = self.client.post('/', post_data)
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 449, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 262, in post
return self.request(**r)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "views.py", line 84, in homepage
print results[0].check_password(form.cleaned_data['password'])
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 304, in check_password
return check_password(raw_password, self.password, setter)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/hashers.py", line 42, in check_password
hasher = get_hasher(algorithm)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/hashers.py", line 115, in get_hasher
"setting?" % algorithm)
ValueError: Unknown password hashing algorithm '123'. Did you specify it in the PASSWORD_HASHERS setting?
You have directly stored the user passowrd as a plain string self.user.password = 123 but django stores user passwords using hashing algorithm that is why you are receiving the error. You can set user password by using set_password method of user which will apply hashing algorithm before saving it:
user.set_password('123')
user.save()