Django CBV form valid to return Ajax response

Django -- Posted on July 17, 2017

Django CBV form valid to return Ajax response

              
                from django.http import JsonResponse
from django.views.generic.edit import CreateView

class MyForm(CreateView):
    def get_form_kwargs(self):
        """
        Returns the keyword arguments for instantiating the form.
        """
        kwargs = super(MyForm, self).get_form_kwargs()
        if hasattr(self, 'object'):
            kwargs.update({'instance': self.object})
        return kwargs
    
   def form_valid(self, form):
        form.save()
        if self.request.is_ajax():
            data = {}
            data['message'] = 'object {} with id: {}'.format(
                form.instance, form.instance.pk)
            return JsonResponse(data)
        else:
            return super(MyForm, self).form_valid(form)
                  
   
            

Related Posts