Dimitris Kougioumtzis Blog About technology

Django CBV form valid to return Ajax response

Category Django

Posted on July 17, 2017



Django CBV form valid to return Ajax response


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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)

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere