Django View возвращает только JSON вместо рендеринга шаблона

В моем Django views.py есть функция, которая должна отрисовывать веб-сайт и возвращать JsonResponse. Обычно, когда я перехожу по URL, я ожидаю увидеть отрисованный сайт. Однако вместо рендеринга шаблона я вижу только JSON-ответ.

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})

Вывод веб-сайта: Вывод веб-сайта

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'})
Вернуться на верх