programing

템플릿 없이 Django에서 빈 응답을 보내려면 어떻게 해야 합니까?

showcode 2023. 3. 11. 09:39
반응형

템플릿 없이 Django에서 빈 응답을 보내려면 어떻게 해야 합니까?

브라우저의 ajax 요청에 응답하는 뷰를 작성했습니다.이렇게 써있어요.

@login_required
def no_response(request):
    params = request.has_key("params")
    if params:
        # do processing
        var = RequestContext(request, {vars})
        return render_to_response('some_template.html', var)
    else: #some error
        # I want to send an empty string so that the 
        # client-side javascript can display some error string. 
        return render_to_response("") #this throws an error without a template.

제가 그걸 어떻게 합니까?

클라이언트측에서의 서버 응답은 다음과 같습니다.

    $.ajax
    ({
        type     : "GET",
        url      : url_sr,
        dataType : "html",
        cache    : false,
        success  : function(response)
        {
            if(response)
                $("#resp").html(response);
            else
                $("#resp").html("<div id='no'>No data</div>");
        }
    });

render_to_response는 템플릿 렌더링 전용 바로가기입니다.그렇게 하기 싫으면 빈칸을 돌려주세요.HttpResponse:

 from django.http import HttpResponse
 return HttpResponse('')

그러나, 이 상황에서는, AJAX에 에러가 있는 것을 시그널링 하고 있기 때문에, 에러 응답(아마도 코드 400)을 반환할 필요가 있습니다.이러한 응답은, 다음의 방법으로 실행할 수 있습니다.HttpResponseBadRequest대신.

빈 답변을 반환하는 가장 좋은 코드는204 No Content.

from django.http import HttpResponse
return HttpResponse(status=204)

단, 이 경우 204는 :를 의미하므로 빈 응답을 반환하지 마십시오.

조금 돌려주는 것이 좋다4xx에러가 클라이언트 측에 있는 것을 보다 정확하게 나타내는 상태 코드.본체에 임의의 스트링을 삽입할 수 있습니다.4xx응답해 주셨으면 합니다만,JSONResponse:

from django.http import JsonResponse
return JsonResponse({'error':'something bad'},status=400)

언급URL : https://stackoverflow.com/questions/4123155/how-do-i-send-empty-response-in-django-without-templates

반응형