必承其重 | 欲带皇冠 2013-12-04 14:58 采纳率: 0%
浏览 40

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 ?

  • 写回答

1条回答 默认 最新

  • weixin_33735676 2013-12-04 15:13
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突