title: how to send a failure response from django to ajax
body: <p>I have this Ajax request:</p>
  <pre><code>    $.ajax({
              url: &quot;my_url&quot;,
              headers: {'X-CSRFToken': '{{ csrf_token }}'},
              type: &quot;post&quot;,
              data:{x:1
                   },
              success: function(response, textStatus, xhr) {
                  alert(response + textStatus + xhr);
  
              },
              error: function(xhr, ajaxOptions, thrownError) {
                  alert(xhr.status + ' Error: ' + thrownError);
              }
            });
  
  }
  </code></pre>
  <p>On the Django side, I sometimes want to propagate errors.<br />
  If I raise an exception, it will propagate as a 500 response INTERNAL ERROR.<br />
  But I want to display an error message.
  So I tried</p>
  <pre><code>return HttpResponse(&quot;Bad permissions&quot;, status=500)
  </code></pre>
  <p>But I'm not able to capture the custom error message.
  Any ideas?</p>
  <hr />
  <p>For those of you who want to know what worked:</p>
  <h2>Javascript in template</h2>
  <pre><code>function send(){
      $.ajax({
              url: &quot;/get_pens/&quot;,
              headers: {'X-CSRFToken': '{{ csrf_token }}'},
              type: &quot;post&quot;,
              data:{x:1
                   },
              dataType: &quot;json&quot;,
              success: function(response, textStatus, xhr) {
                  alert('Success: ' + response + textStatus + xhr);
  
              },
              error: function(xhr, ajaxOptions, thrownError) {
                  alert(xhr.status + ' Error: ' + xhr.responseJSON['err']);
              }
            });
  }
  </code></pre>
  <h2>views.py</h2>
  <pre><code>def get_pens(request):
      pens = []
      response = HttpResponse(json.dumps({'pens': pens, 'err': 'some custom error message'}), 
          content_type='application/json')
      response.status_code = 400
      return response
  </code></pre>