[Answered ]-Django: ajax view structure

2👍

There are valid reasons for checking is_ajax, for one it’s a good way to take advantage of the cross-domain policy.

In that case I’d return a 403 – Forbidden. Note that 403 has nothing to do with authorization – it’s an acknowledgement that you’ve received and understood the request, and are refusing to return anything, which exactly matches your intent. You can optionally include the reason why the request is refused:

You can use the status parameter to set the status on a regular HttpResponse object, or use the HttpResponseForbidden subclass:

return HttpResponseForbidden("Request must be a valid XMLHttpRequest")

Personally, I tend to re-use the same views to serve either a template to a regular GET, or JSON to an ajax request. I don’t know if I’d consider that a best practice or anything, it just seems to be what is needed for my projects.

0👍

If you don’t know what you want in the else clause, are you sure you need the if? Why test for is_ajax at all? Why not just return JSON data to the browser?

Leave a comment