Home > front end >  Send request to View Django, without receiving any response
Send request to View Django, without receiving any response

Time:12-06

I ask the user a question on my website and if the answer is yes, I will send two data to view Django using a JavaScript file and using Ajax. I want to get this data in View Django and not send any HttpResponse to the user. If we do not send a response in the view, it will give an error. How should I do this?

When the condition if request.is_ajax (): Runs, I get the following error:

ValueError: The view tourist.views.planing did not return an HttpResponse object. It returned None instead.

Thanks


def planing(request):   
          
    if request.is_ajax():
        # Get user location from user location.js file:
        latitude = request.POST.get('latitude', None)
        longitude = request.POST.get('longitude', None)

        # To save data
        request.session['latitude'] = latitude
        request.session['longitude'] = longitude


    elif request.method == "GET":
        return render(request, "tourist/planing.html")
        
          
    elif request.method == "POST":
        # To retrive data:
        latitude = request.session.get('latitude')
        longitude = request.session.get('longitude')
        if latitude is not None :
            latitude = float(latitude)
            longitude = float(longitude)
       
        .
        .
        .
        return render(request, "tourist/map.html")


CodePudding user response:

You can return an empty JSON. Like so:

from django.http import JsonResponse

if request.is_ajax():
    # Get user location from user location.js file:
    latitude = request.POST.get('latitude', None)
    longitude = request.POST.get('longitude', None)

    # To save data
    request.session['latitude'] = latitude
    request.session['longitude'] = longitude
    return JsonResponse({})

This will ensure there is a response back to the AJAX request.

  • Related