How to store an object in django sessions framework - django

I have an django and i am trying to store an object in django session varaible, and trying to access that in the redirected view, but its showing keyerror as below
def payment(request):
if request.method == 'POST':
form = CardForm(request.POST)
if form.is_valid():
data = form.cleaned_data
response = response_from_payment_gateway(data)
request.session['response'] = response
return HttpResponseRedirect(reverse('paygate:payment_success'))
else:
form = CardForm(initial={'number':'4242424242424242'})
return render_to_response('payment_form.html',{'form': form})
def PaymentSuccess(request):
print request.session['response'],"=================>"
response = None
return render_to_response("payment_success.html", {'response':response}, context_instance=RequestContext(request))
Result
Internal Server Error: /payment/success/
Traceback (most recent call last):
File "/home/Envs/app/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/user/virtualenvironment/apps/app/payment/views.py", line 120, in PaymentSuccess
print request.session['response'],"=================>"
File "/home/Envs/app/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
KeyError: 'response'
So i am getting back a response object from the payment gateway that contains the transaction details, and i am trying to save that in session framework variable called response as above.
And i am trying to access the variable called response in the redirected view PaymentSuccess as request.session['response'], and getting the above mentioned error.
so how can we send/save the objects in the sessions in django ?
In above the response object will be of the following form
{'status': 'SUCCESS', 'response': <Charge charge id=ch_2OXdxxxxNVw at 0xb508e76cL> JSON: {
"amount": 100,
"amount_refunded": 0,
"balance_transaction": "txxxn_xxxxxxxxO",
"captured": true,
"currency": "usd",
"customer": null,
"description": null,
}}

the interpreter never reaches this part
request.session['response'] = response
this means that either our form isn't valid or the method of the request isn't POST
try to replace
if request.method == 'POST':
with
if request.POST:
and if it doesn't work set the request.session['response'] to any other value just to make sure that the sessions framework isn't broken.
You need to debug further, I'm 100% sure that this isn't a session problem.

Related

Django REST API: How to respond to POST request?

I want send POST request with axios(VueJS) and when Django server got a POST request then I want to get back that request message.
I tried make functions when got an POST request in Django server and then return JsonResponse({"response": "got post request"), safe=False)
JS function
sendMessage() {
axios({
method: "POST",
url: url,
data: this.message
})
.then(response => {
this.receive = response;
})
.catch(response => {
alert('Failed to POST.' + response);
})
}
}
views.py
from chat.serializer import chatSerializer
from chat.models import *
from rest_framework.routers import DefaultRouter
from rest_framework import viewsets
from django.http import JsonResponse
from django.views.generic import View
# Create your views here.
class get_post(View):
def post(self, request):
if request.method == 'POST':
JsonResponse({"response": 'got post request'}, safe=False)
but error says like that in django
Internal Server Error: /api/chat/
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line
47, in inner
response = get_response(request)
File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 188,
in _get_response
self.check_response(response, callback)
File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 309,
in check_response
raise ValueError(
ValueError: The view chat.views.views.get_post didn't return an HttpResponse object. It returned None instead.
[26/Oct/2022 17:06:51] "POST /api/chat/ HTTP/1.1" 500 60946
I think POST request is working properly, but Django code is something wrong.
Therefore, my question is..
How to fix and solve this error?
When I call axios in JS, inside '.then' we got a response so which data is come to this variable? Should I return this data like Response() or JsonResponse() method?
just add a return in the view ... like this:
class get_post(View):
def post(self, request):
if request.method == 'POST':
return JsonResponse({"response": 'got post request'}, safe=False)
because the error complains that the post function must return anything.
for the second question ya you need to return JsonResponse because you are dealing with APIs.

Why it is occuring KeyError: 'main' and how to solve it

I am having keyerror: 'main'. I have searched many sites, but still can't find any satisfactory answer to solve this error. I would really appreciate if someone can give me some pointers. Thanks in advance.
I have tried solving this by adding a function on the init.py which is suggested by a site. But it still didn't work.
https://forum.inductiveautomation.com/t/error-on-sys-modules/6431/2
code: view.py
from django.shortcuts import render
import requests
from .models import City
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=MYKey'
cities = City.objects.all() # return all the cities in the database
city = 'Dhaka'
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_data = []
for city in cities:
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_app = {
'city': city,
'temperature': city_weather['main']['temp'],
'description': city_weather['weather'][0]['description'],
'icon': city_weather['weather'][0]['icon']
}
# add the data for the current city into our list
weather_data.append(weather_app)
#context = {'weather' : weather_app}
context = {'weather_data': weather_data}
# returns the index.html template
return render(request, 'weather_app/index.html')
terminal:
(env) acer#acer-Aspire-V3-472P:~/DjangoProject/Weather$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
May 03, 2019 - 06:48:01
Django version 2.2, using settings 'Weather.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/acer/DjangoProject/Weather/weather_app/views.py", line 30, in index
'temperature': city_weather['main']['temp'],
KeyError: 'main'
[03/May/2019 06:48:18] "GET / HTTP/1.1" 500 68977
You don't check that the data for the specific city is found. You loop through all cities in your database, and try to get the weather for each one; but you don't check that the result is actually returned. You should do:
for city in cities:
response = requests.get(url.format(city))
if response.status_code == 404:
continue
city_weather = response.json()
Also, you should check that you are formatting your URL properly. As it stands, you are inserting your City object directly into the URL - this will only work if you have defined a __str__ method that returns only the city name. It would be better to use the name directly:
response = requests.get(url.format(city.name)) # or whatever the name field is
I'm not sure. I have a suggestion. You may check the city_weatherdata (using print())before making weather_app to see if the key'main'is really in city_weather, maybe the key happened not to be in the data.

Post query to API in Django REST

I have code in Angular 2:
sendPost(){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let requestOptions = new RequestOptions({headers: headers});
requestOptions.headers = headers;
let data = {
"name": "XX",
"email": "xxx#op.com",
"phone_number": "+99999995555",
"address": "YYY",
"code": "80-885",
"city": "YHYY",
"voivodeship": "ZZZZ",
"description": "VVVVV"
};
this.http.post(`http://127.0.0.1:8000/companies/create`, data, requestOptions).subscribe(res => {
console.log(res.json());
}, (err) => {
console.log(err);
});
}
Error API:
<WSGIRequest: OPTIONS '/companies/create'>
Internal Server Error: /companies/create
Traceback (most recent call last):
File "C:XX\CRM\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:XX\CRM\env\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view my_crm.views.companies_create didn't return an HttpResponse object. It returned None instead.
[25/Jul/2017 21:32:35] "OPTIONS /companies/create HTTP/1.1" 500 59515
The API shows that there is an error somewhere in the function but when I use POSTMAN this is identical JSON goes through with no problem. Where can be the error?
I think the API is well handled when testing using POSTMAN.
EDIT:
API function:
#csrf_exempt
def companies_create(request):
"""
Create a new company.
"""
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = CompanySerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
The solution is to replace:
headers.append('Content-Type', 'application/json');
to:
headers.append('Content-Type', 'application/x-www-form-urlencoded');
I'm not able to explain this because I'm sending a JSON file. Maybe someone will explain what this is about?

Just updated to Django 1.4 and getting 'WSGIRequest' object has no attribute 'SUCCESS' error

I just upgraded to Django 1.4 and am getting the following error:
'WSGIRequest' object has no attribute 'SUCCESS'
Traceback:
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/spicestore/apps/account/views.py" in login
87. messages.add_message(request.SUCCESS,
Exception Type: AttributeError at /account/login/
Exception Value: 'WSGIRequest' object has no attribute 'SUCCESS'
Anyone know what could be causing it?
Here's the actual code in views.py:
messages.add_message(request.SUCCESS,
ugettext(u"Successfully logged in as %(user)s.") % {
"user": user_display(form.user)
}
messages.add_message(request,
messages.SUCCESS,
ugettext(u"Successfully logged in as %(user)s.") % { "user": user_display(form.user) })
or FASTER:
messages.success(request,
ugettext(u"Successfully logged in as %(user)s.") % { "user": user_display(form.user) })
See:
https://docs.djangoproject.com/en/dev/ref/contrib/messages/#using-messages-in-views-and-templates

How to correctly make a POST call to Facebook Graph API in django

I am trying to create an Facebook Event from my local application and I have a form where a user enters the event information. According to this, I have to make a post call to https://graph.facebook.com/USERID/events
To do so I've used urlopen as such
form_fields = {
"access_token": request.user.get_profile().access_token,
"name" : "name",
"start_time" : "01/01/2012"
}
urllib2.urlopen(update_url,urllib.urlencode(form_fields))
Running the code I get
HTTP Error 400: Bad Request
and after debugging the program the variable values are
update_url = str: https://graph.facebook.com/XXXXXXXX/events
form_fields = dict: {'access_token': u'XXXXXX', 'start_time': datetime.datetime(2012, 1, 6, 0, 0), 'location': 'someplace', 'name': u'ab'}
The update_url seems to be correct and I'm guessing the problem is with form_fields. So how should I give these fields to Facebook Graph API?
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Akshay\workspace\example\example\planpouchproto\views.py" in createPouch
20. graph.post('%s/events' %request.user.get_profile().facebook_id, **{"access_token": request.user.get_profile().access_token,"name" : cd['event_name'],"start_time" : "01/01/2012"})
File "C:\Users\Akshay\workspace\example\example\facepy\graph_api.py" in post
65. retry = retry
File "C:\Users\Akshay\workspace\example\example\facepy\graph_api.py" in _query
240. return load(method, url, data)[0]
File "C:\Users\Akshay\workspace\example\example\facepy\graph_api.py" in load
196. result = self._parse(response.content)
File "C:\Users\Akshay\workspace\example\example\facepy\graph_api.py" in _parse
282. error.get('code', None)
Exception Type: OAuthError at /pouch/
Exception Value:
Facepy makes the interaction with Facebook simpler, give it a try.
Posting an event to the graph would be something like
graph.post('USERID/events', form_fields)
To debug, you can test if authentication works by posting a comment:
graph = GraphAPI(request.user.get_profile().access_token)
graph.post(path="me/feed", message="hello FB", caption="hello FB", description="hello FB")
Then you can narrow down your problem.