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
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.