I have these methods:
def get_all_from_database():
urls = Url.objects.all()
ips = Ip.objects.all()
context = {
'urls': serializers.serialize('json', urls),
'ip': serializers.serialize('json', ips)
}
return context
and the method that sends data to using ajax:
def send_results(request):
if request.is_ajax():
address = request.POST.get('url')
process_data(address, email_to, email_from)
context = get_all_from_database()
return HttpResponse(json.dumps(context), content_type='application/json')
But this raises error : INTERNAL SERVER ERROR 500 'dict' object has no attribute '_meta'.
Wheres the mistake, and how to correct it ?
You cant use serializers.serialize method with dict list that you got from values call:
urls = Url.objects.all().values('address', 'cnt')
Use default queryset:
urls = Url.objects.all()
ips = Ip.objects.all()
In you example context['urls'] value already in json format, and you cant use json.dumps() for json data.
You can use this example:
json.dumps({
'urls': Urls.objects.all().values_list('address', 'cnt'),
'ips': Ip.objects.all().values_list('address', 'cnt')
}), 'json')
urls = Url.objects.all().values('address', 'cnt')
ips = Ip.objects.all().values('address', 'cnt')
The above lines returns dict objects, try:
urls = Url.objects.all().values('address', 'cnt').values_list()
ips = Ip.objects.all().values('address', 'cnt').values_list()
Then you will have urls as a list containing the tuples:
[(address_1, cnt_1), (address_2, cnt_2), ...]
see: QuerySet API reference
I think it should be :
res=json.dumps({
'urls': list(Urls.objects.all().values_list('address', 'cnt')),
'ips': list(Ip.objects.all().values_list('address', 'cnt'))
}), 'json')
return HttpResponse(res,content_type="application/json")
Related
Trying to run this code to get the topstories from hacker news is giving me this error 'TypeError: list indices must be integers or slices, not str', the error is generated at
story = data['story']
from multiprocessing import context
from django.shortcuts import render
import requests
# Create your views here.
def index(request):
#make an api call and save response
url = f'https://hacker-news.firebaseio.com/v0/topstories.json'
response = requests.get(url)
data = response.json()
story = data['story']
context = {
'story': story
}
return render(request, 'SyncNews/index.html', context)
What can I do to correct this error as I'm following a video showing a similar project but this error was not seen, I've also tried removing the '' but receive an error 'UnboundLocalError at /
local variable 'story' referenced before assignment'
story = data['story']
Your 'data' is a list of numbers, not a dictionary. Depending on whether you want to have one or more numbers from that list you can do one of such options:
# first number:
def index(request):
...
data = response.json()
story = data[0]
context = {
'story': story
}
return render(request, 'SyncNews/index.html', context)
# list of numbers:
def index(request):
...
data = response.json()
context = {
'story': data
}
return render(request, 'SyncNews/index.html', context)
I have a problem with django-pytest
I'm using, djnago-rest-framework
There is a problem testing the details. As shown in the code below, I entered the same details, detail1, detail2, and detail3 codes. However, only detail1 succeeds and detail2, detail3 indicates that '/api/v1/stats/1/' could not be found. It also occurs when implementing delete. I am curious about the cause and solution of this error.
enter image description here
// tests/test_apis.py
import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from stats.models import Stats
class StatsApiTests(APITestCase):
def setUp(self):
Stats.objects.get_or_create(blockshots=1, memo='test1')
Stats.objects.get_or_create(blockshots=2, memo='test2')
self.create_read_url = reverse('api:stats:stats-list')
self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': '1'})
def test_detail1(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_detail2(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_detail3(self):
response = self.client.get(self.read_update_delete_url)
data = json.loads(response.content)
content = {
'blockshots': 1,
'memo': 'test1',
}
self.assertEqual(data, content)
def test_list(self):
response = self.client.get(self.create_read_url)
self.assertContains(response, 'test1')
self.assertContains(response, 'test2')
Its hard to know what your actual implementation for read_update_delete_url, hence I assume it is looking up the resource by primary key. In that case, you can simply add the primary key in the url like this:
stat_one, _ = Stats.objects.get_or_create(blockshots=1, memo='test1')
stat_two, _ = Stats.objects.get_or_create(blockshots=2, memo='test2')
self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': stat_one.pk})
Basically, get_or_create returns the object and the state of the object (created or not). You can use the object's id as the parameter of reverse function.
Trying to get data from google books API but it is showing the error ' 'method' object is not subscriptable'
I know the “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using round brackets after the name of the method you want to call.
def books(request):
if request.method == "POST":
form = DashboardForm(request.POST)
text = request.POST['text']
url = 'https://www.googleapis.com/books/v1/volumes?q='+text
r = requests.get(url)
answer = r.json
result = []
for i in range(10):
result_dict= {
'title':answer['items'][i]['volumeInfo']['title'], # This line is showing error.
'subtitle': answer['items'][i]['volumeInfo']['title'].get('subtitle'),
'description': answer['items'][i]['volumeInfo']['title'].get('description'),
'count': answer['items'][i]['volumeInfo']['title'].get('pageCount'),
'categories': answer['items'][i]['volumeInfo']['title'].get('categories'),
'rating': answer['items'][i]['volumeInfo']['title'].get('pageRating'),
'thumbnail': answer['items'][i]['volumeInfo']['title'].get('imageLinks'),
'preview': answer['items'][i]['volumeInfo']['title'].get('previewLink')
}
result.append(result_dict)
context={
'form':form,
'results':result,
}
return render(request,'dashboard/books.html',context)
else:
form = DashboardForm()
context = {'form':form}
return render(request,'dashboard/books.html',context)
In line 7, you write:
answer = r.json
But r.json is a method which you should call:
answer = r.json()
So I have JSON request with format like this:
{
"item_ids": [635,10,692,194,9412],
"gender": "male",
"number_results": 5
}
I'm trying to parse array in "item_ids". But I got error message like in the title. This is my code:
resto_id = json.loads['item_ids']
data = json.dumps(resto_id)
I also tried this:
response = requests.get("http://127.0.0.1:8520/recommend_multi")
users = json.loads(response.text)
data = users['item_ids']
But gave me an error:
TypeError: Object of type JSONDecodeError is not JSON serializable
Edit: Maybe this will help:
#app.route('/recommend_multi', methods=['POST'])
def recommend_multi():
dct={}
new_user = 'newusername'
try:
e=""
resto_id = json.loads['item_ids']
data = json.dumps(resto_id)
# response = requests.get("http://127.0.0.1:8520/recommend_multi")
# users = json.loads(response.text)
# data = users['item_ids']
gender = request.json['gender']
resto_rec = float(request.json['number_results'])
input_dict = {'id_resto': data,
'gender': [gender, gender, gender, gender, gender], 'username': [new_user, new_user, new_user, new_user, new_user]}
dct = {"items": input_dict}
dct2 = {"data": dct, "message":"sukses", "success":True}
except Exception as e:
dct2 = {"data": dct, "message":e, "success":False}
return jsonify(dct2)
And this is the traceback:
I run it with docker. And for request I'm using Insomnia
The problem is in this snippet:
except Exception as e:
dct2 = {"data": dct, "message":e, "success":False}
You are basically trying to JSON serialize the exception e which is not possible. You need to use something that is JSON serializable, like the string representation of the exception, for example by using str(e):
except Exception as e:
dct2 = {"data": dct, "message":str(e), "success":False}
First, thanks to #bdbd to keep responding to me. The exception solution helped me to fix my code, but in the end I managed to debug my code then found the solution which is resolve my problems about retrieving array in JSON objects. So instead of this:
resto_id = json.loads['item_ids']
data = json.dumps(resto_id)
I need to request first.
resto_id = request.json
data = json.dumps(resto_id)
data2 = json.loads(data)
#Then retrieve the array
data2["item_ids"]
this is the call back URL which am getting from the payment gateway I am integrating with
http://127.0.0.1:8000/checkout/mfsuccess/?paymentId=060630091021527961&Id=060630091021527961
I want to extract the paymentId int from this URL so I can use it in my function
this is the URL line am using
path('checkout/mfsuccess/?<str:paymentId>', gateway_Success, name='mf_success'),
and this is my function
def gateway_Success(request, id):
payment_id = request.GET.get('id')
print(payment_id)
context = {
"payment_id": payment_id
}
return render(request, "carts/checkout-mf-success.html")
How I do that since the way am doing not working I am getting the following error
Not Found: /checkout/mfsuccess/
[20/Nov/2020 03:38:59] "GET /checkout/mfsuccess/?paymentId=060630091121528060&Id=060630091121528060 HTTP/1.1" 404 4378
You don't need to adjust your path() function to catch the URL query parameters
path('checkout/mfsuccess/', gateway_Success, name='mf_success'),
also, change your view as,
def gateway_Success(request):
id_ = request.GET.get('Id') # retrieving the `Id`
payment_id = request.GET.get('paymentId') # retrieving the `paymentId`
context = {
"payment_id": payment_id,
"id_": id_
}
return render(request, "carts/checkout-mf-success.html", context=context)
This is enough to catch the redirection.