Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.

Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?

For example, can I still use the HttpResponse with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON.

1 Answer

0 votes
by (106k points)

import json 

from django.http import HttpResponse 

from django.views.generic.edit import CreateView 

from myapp.models import Author 

class AjaxableResponseMixin(object): 

def render_to_json_response(self, context,


data = json.dumps(context)

response_kwargs['content_type'] = 'application/json' 

return HttpResponse(data, **response_kwargs) 

def form_invalid(self, form):

response = super(AjaxableResponseMixin,


if self.request.is_ajax():

return self.render_to_json_response(form.errors, status=400) 


return response

def form_valid(self, form): 

response = super(AjaxableResponseMixin, self).form_valid(form) 

if self.request.is_ajax(): 

data = { 'pk':, 

return self.render_to_json_response(data) else: 

return response 

class AuthorCreate(AjaxableResponseMixin, CreateView):

model = Author fields = ['name']

Browse Categories