[Answered ]-How to redirect to page where request came from in Django

1👍

Typically for that, the server responds with a 405 method not allowed. Especially since it is not even said that the request "comes from somewhere". For example one can make such request with curl, wget, etc. You can work with a @require_POST decorator [Django-doc] for example to return a 405 in case the method is something else than a POST (GET, PUT, PATCH, etc.):

from django.views.decorators.http import require_POST

@require_POST
def delete_patient(request):
    patient_id = request.POST['patient_id']
    rem = Patient.objects.get(pk=patient_id)
    rem2 = CustomUser.objects.get(aid=patient_id, role=4)
    rem.delete()
    rem2.delete()
    return JsonResponse({'delete': 1})

If you really want to redirect to the referring page, you can try to access the HTTP_REFERER key from the request.META dictionary. But not all browsers per se send the referring page, and it is not even said that the request comes from a web client in the first place.

You thus can work with:

from django.http import HttpResponseNotAllowed, HttpResponseRedirect

def delete_patient(request):
    if request.method == 'POST':
        patient_id = request.POST['patient_id']
        rem = Patient.objects.get(pk=patient_id)
        rem2 = CustomUser.objects.get(aid=patient_id, role=4)
        rem.delete()
        rem2.delete()
        return JsonResponse({'delete': 1})
    elif 'HTTP_REFERER' in request.META:
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    else:
        return HttpResponseNotAllowed(['POST'])

Leave a comment