The views handling AJAX requests have not special magic. They have only specific headers in response.
For example, I use my custom decorators for AJAX views.
# to set cookies in IE
import json as json2
from django.http import HttpResponse
def _setP3P( response ):
response["P3P"] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"' # to set up cookies in AJAX views (for Internet Explorer)
def json( view ):
def response( *args, **kwargs ):
request, data = view( *args, **kwargs )
response = HttpResponse( json2.dumps( data ),
content_type = 'application/json' )
_setP3P( response )
return response
return response
The example of using:
@json
def set_photo_mark( request ):
req = request.REQUEST
# actions here
return request, { 'result': "OK" } # json response
The view above generates json answer.
You can include it into your urls.py by a standart way:
urlpatterns = patterns('',
( r'^set-photo-mark', 'phapp.views.set_photo_mark' ),
)
Then you can do usual AJAX calls to /set-photo-mark/.
For non-ajax views I have another decorator: template.
def template( template = None ):
def template_inner( view ):
def response( *args, **kwargs ):
args_list = list( args )
request = args[ 0 ]
del args_list[ 0 ]
request, result = view( request, *args_list, **kwargs )
req = request.REQUEST
if type( result ) == dict:
" Result is out. "
t = loader.get_template( template )
c = RequestContext( request, result )
response = HttpResponse( t.render(c),
content_type = 'text/html' )
elif type( result ) == type( None ):
response = HttpResponseNotFound( request )
else:
response = redirect( result )
_setP3P( response )
return response
return response
return template_inner
This is also easy to use:
@template( "index.html" )
def index( request ):
req = request.REQUEST
user_id = req[ 'oid' ]
# actions...
if True:
# an example of using the current template index.html
return request, { 'sid': user_id,
'user_id': req[ 'oid' ],
'PHOTOS_ROOT_URL': PHOTOS_ROOT_URL
}
else:
return request, '/help/' # an example of redirection to /help/
And you can make wrapped templates to emulate view inheritance.