Django和Ajax管理

I am trying to understand how manage greatly the ajax system request with the framework Django. I would like create another views.py in one on my app in order to manage only ajax requests.

My first views.py

def my_playlists(request) :
   if not request.user.is_authenticated() :
       return HttpResponseRedirect('/login/')
    playlists = Playlist.objects.filter(user_id=request.user.id)
    return render(request, 'playlists/my_playlists.html', {'playlists' : playlists})

And a second views.py where I can call ajax request from jquery.

@csrf_exempt
def getTemplateForm(request) :
   if request.is_ajax() :
      id_song = request.POST['id_song'];
      music = get_object_or_404(Music, pk=id_song)
      author = music.author
      title = music.title
      return render(request, 'playlists/edit-form-song.html', {'author' : author, 'title' : title})

I think it's better to seperate ajax and action methods. So it is possible to create another view ? And how I do with urls.py ?

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.