'Getting error in Python: 'NoneType' object has no attribute 'json'

Getting error in Python: 'NoneType' object has no attribute 'json'

How to solve this error?

Below is my code: views.py

from django.shortcuts import render
from django.http import HttpResponse
#from django.shortcuts import render
import json
import dotenv
#from . models import Contect
from flask import Flask, render_template, Response
from rest_framework.response import Response
# Create your views here.
    
def home1(request):
   # get the list of todos
   response1 = request.GET.get('https://jsonplaceholder.typicode.com/todos/')
   # transfor the response to json objects
   todos = response1.json()
   return render(request, "main_app/home.html", {"todos": todos})


Solution 1:[1]

Two errors I see here: Change this:

response1 = request.GET.get('https://jsonplaceholder.typicode.com/todos/')

TO:

response1 = request.get('https://jsonplaceholder.typicode.com/todos/')

Also, check first if response1 is not empty. It is empty, hence you get that error.

Solution 2:[2]

You can try retrieving the JSON values from the URL following this method -

from urllib.request import urlopen

def home1(request):
    # get the list of todos
    response1 = urlopen('https://jsonplaceholder.typicode.com/todos/')
    # transfor the response to json objects
    todos = json.loads(response1.read())
    return render(request, "main_app/home.html", {"todos": todos})

todos will hold all the JSON values that the URL provided.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Devang Sanghani
Solution 2 Mehadi