Django和Ajax管理


                    

我试图了解如何使用Django框架极大地管理ajax系统请求。
我想在我的应用程序中一个创建另一个views.py,以便仅管理ajax请求。</ p>

我的第一个views.py </ p>

  def my_playlists(request):
    如果不是request.user.is_authenticated():
        返回HttpResponseRedirect('/ login /')
     播放列表= Playlist.objects.filter(user_id = request.user.id)
     返回render(request,'playlists / my_playlists.html',{'playlists':播放列表})
</ code> </ pre>

还有第二个views.py,我可以在其中调用jquery的ajax请求。</ p>

  @csrf_exempt
def getTemplateForm(request):
    如果request.is_ajax():
       id_song = request.POST ['id_song'];
       音乐= get_object_or_404(音乐,pk = id_song)
       作者= music.author
       标题= music.title
       返回渲染(请求,“播放列表/edit-form-song.html”,{“作者”:作者,“标题”:标题})
</ code> </ pre>

我认为最好分开使用ajax和action方法。
因此可以创建另一个视图吗? 以及我如何处理urls.py?</ p>
     </ div>

展开原文

原文

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个回答

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐