skip to Main Content

I am trying to write a webpage in Django that obtains real-time input from the user and gives some responses back to the user. However, when the function in views.py returns a type of JsonResponse, my HTML file in the template cannot be showed properly. How can I fix this issue?

My HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Real-time Input Text</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <input type="text" id="input-box">
  <div id="output"></div>

  <script>
    $(document).ready(function() {
      $("#input-box").on("input", function() {
        var inputText = $(this).val(); // Get the current value of the input box

        $.ajax({
          url: "/update_text/",
          method: "POST",
          data: {
            text: inputText
          },
          success: function(response) {
            $("#output").text(response);
          }
        });
      });
    });
  </script>
</body>
</html>

My function in views:

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

def update_text(request):
    if request.method == "POST":
        text = request.POST.get("text", "")

        return JsonResponse(text, safe=False)
    else:
        return JsonResponse({}, status=400) 

2

Answers


  1. You should return render and pass your data as context

    return render(request, template_name, context)
    
    Login or Signup to reply.
  2. Rendering a template is not possible with JsonResponse.

    You can check the request headers, particularly the accept header. and if is application/json then return the JsonResponse, otherwise return render(...).

    def update_text(request):
        if request.accepts('application/json'):
           return JsonResponse(..)
        else:
           return render(..) 
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search