Dimitris Kougioumtzis Blog About technology

django ajax mixin

Category Django

Posted on Sept. 8, 2017



django ajax mixin


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.http import JsonResponse


class CustomAjaxFormMixin(object):
    '''
    This mixin is used with Class-Based FormViews
    '''
    def form_valid(self, form):
        obj = form.save()
        if self.request.is_ajax():
            msg = {'data': 'The object saved with id - {}'.format(obj.pk)}
            return JsonResponse(msg)
        else:
            return super(CustomAjaxFormMixin, self).form_valid(form)

    def form_invalid(self, form):
        if self.request.is_ajax():
            msg = {}
            for key, value in form.errors.items():
                for field in form:
                    if field.name == key:
                        msg[field.label] = value
            return JsonResponse(msg)
        else:
            return super(CustomAjaxFormMixin, self).form_invalid(form)

About

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

Elsewhere