[Django]-Django returning status code 400 with error message from view

8๐Ÿ‘

โœ…

If I understand you right, you can return 400 with some context:

context = {
   'reason': 'your reason'
}
response = render(request, '400.html', context)
response.status_code = 400
return response

and for cases with ajax, you just return HttpResponse:

context = {
    'status': '400', 'reason': 'you can access this view only via ajax'  
}
response = HttpResponse(json.dumps(context), content_type='application/json')
response.status_code = 400
return response

and in your js code:

$.ajax({
    // ... 
    // ...
}).fail(function(data){
    var status = data.status;
    var reason = data.reason; 
});
๐Ÿ‘คdoniyor

Leave a comment