Django apps using class-based views and ajax?

后端 未结 3 1345
逝去的感伤
逝去的感伤 2021-01-31 04:50

I\'m learning Django and I found class-based views and I wonder how to implement Ajax on those views.

I searched github for a django project and I found some using class

3条回答
  •  情话喂你
    2021-01-31 05:51

    If you want to support both AJAX and traditional views, you can add something like this to your CreateView:

    # at top of file
    from django.http import JSONResponse  
    
    # inside CreateView class
    def render_to_response(self, context, **response_kwargs):
        """ Allow AJAX requests to be handled more gracefully """
        if self.request.is_ajax():
            return JSONResponse('Success',safe=False, **response_kwargs)
        else:
            return super(CreateView,self).render_to_response(context, **response_kwargs)
    

    This handles regular views normally (with redirect etc.) but for AJAX, it return a JSONResponse instead. Where it returns 'Success', you may want to add more sophisticated logic but this is the basic idea.

提交回复
热议问题