Django View Only Returns JSON Instead of Rendering Template

In my Django views.py, I have a function that is supposed to both render a website and return a JsonResponse. Normally, when I visit the URL, I expect to see the rendered website. However, instead of rendering the template, the only thing I see is the JSON response.

def chatbot(request):
    if request.method == 'POST':
       message = request.POST.get('message')
       response = 'hi hi hi'
       print(message)
       return JsonResponse({'message': message, 'response':response})
     return render(request, 'chatbot.html',{'response':response})

Web site output: web site output

the only thing I see is the JSON response.

That makes perfect sense, a return in Python stops the code flow of the function, and returns the result of the expression next to it, so in this case the JsonResponse.

But even if that somehow would not be the case, it makes no sense: a HTTP request is normally answered with a single HTTP response, not two. How would you even handle such response: what would the browser do with two responses?

If you want to work with AJAX for example, you usually work with a different view to return the JSON response, you can abstract away common logic.

your issue is caused by the incorrect indentation of return render(...) statement.

from django.http import JsonResponse
from django.shortcuts import render

def chatbot(request):
    if request.method == 'POST':
        message = request.POST.get('message')
        response = 'hi hi hi'
        print(message)
        return JsonResponse({'message': message, 'response': response})
 # please ensure this is executed for get requests.
    return render(request, 'chatbot.html', {'response': 'hi hi hi'})
Back to Top