tags:

views:

115

answers:

2

I want to know the correct way to structure ajax views in django.

say i do something like :


def foo_json(request):
    if is.ajax():
        # return JSON here

and make it available as a resource at something like '/foo/data/'..

all is fine..

but if I point the browser at '/foo/data/' .. obviously I get an error (debug) like: app.views.foo_json didn't return an HttpResponse object.

so... my question is:

Whats the best way structure this kind of view?

..should I return an HTTP response code ..maybe 404 / 405 ... or something else? - not sure of the best way to handle this, any advice appreciated :)

EDIT: ..the use-case that triggered this question was ajax PROXY view :


def foo_proxy(request):
    if is.ajax():
        # proxy external URL
        # return resource
    else: 
        # ? do what with browser request
A: 

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?

Ned Batchelder
good point :) ..but I meant it as general question - sometimes it might be appropriate - to keep things clean on the frontend when javacsript is disabled... - I dont always want to return ANYTHING if request is not ajax ... but maybe my thinking is mixed up ..
zack
+1  A: 

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.

Chris Lawlor