pythondjangodjango-views

How to redirect to page where request came from in Django


I currently work on a project an i want to redirect to page where request is came form, when request method is GET.

this is my views.py file Views.py

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})
    else:
        // //

so please tell me what I want to write in else part of view.


Solution

  • 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 (yes, with one R, not HTTP_REFERRER) from the request.META [Django-doc] 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'])