Python Error:Exception Value:can only concatenate str (not “bytes”) to str

error source code:

#Receive request data
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET:
        message = 'You searched for: ' +request.GET['q'].encode('utf-8')
    else:
        message = 'You submitted an empty form'
    return HttpResponse(message)

code marked red position, we can see that encode function is used to transcode, because encode transcode returns data of type Bytes, can not be directly added with data of type STR.

Since the request request has been transcoded in the first sentence of the function, we remove the following encode function here, and the error can be solved.

The updated code is:

#Receive request data
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET:
        message = 'You searched for: ' +request.GET['q']
    else:
        message = 'You submitted an empty form'
    return HttpResponse(message)

Similar Posts: