How to Solve Error Message ‘str’ object has no attribute ‘get’ when returning String Value to an Index Page of Django Application

Posted on

Introduction

In this article, the main focus is just to show Actually, there is another article exist previously. That article has the same content and also similar title with this one. In order to see the information exist in that article, just visit ‘How to Solve Error Message : AttributeError: ‘str’ object has no attribute ‘get’ in Django‘. Actually, this error appear upon trying to change the index page of a Django application. It exist in the article of ‘How to Change Default Page of a Django Application‘. But upon editing the file with the name of ‘views.py’, it will return a value in the index method. That return  value will appear in the main index page.

How to Solve Error Message ‘str’ object has no attribute ‘get’

Actually, in the step of changing index page of the default page of running Django application, it generate error message. The error message itself actually exist upon the definition of index method in ‘views.py’ file. Below is the actual content of the ‘views.py’ of the application folder :

from django.shortcuts import render
# Create your views here.
def index(request):
    return "<h1> Hello World</h1>"

In other words, there is a method with the name index in the ‘views.py’. It will process the main URL of ” when accessing Django application. The main purpose is that Django application will return a string with an HTML format of “<h1> Hello World</h1>” to the page. So, Django application will render it and print Hello World with a h1 style. But apparently, it is not working. Instead of printing ‘Hello World’ in heading 1 style, it trigger the error message. So, the solution will be revising the ‘return’ statement. Actually a HTTP GET Request to the ” URL of the Django application does not require a string value return in the form of HTML script. Revise it as follows :

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
    return HttpResponse("<h1> Hello World</h1>")

Import a HTTPResponse library and use it to return the HTML source code. After editing the source of the ‘views.py’ above just run or access the ” URL Django application once more. If there are no more error appear, it will display a page with Hello World printed in the page with the style of heading 1.

Leave a Reply