R
R
Romua1d2016-11-04 13:52:47
Django
Romua1d, 2016-11-04 13:52:47

ajax handling in cbv how?

def form_invalid(self, form):
        if self.request.is_ajax():
            data = {
                'code': 0,
                'message': form.errors

            }
            return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_invalid(form)
            return response

    def form_valid(self, form):
        form.instance.subject = "Заявка перезвонить № " + str(random.randint(1, 999999))
        form.instance.type = "1"

        if form.instance.phone == '':
            if self.request.is_ajax():
                data = {
                    'code': 0,
                    'message': 'Проверьте информацию',
                }
                return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_valid(form)
            if self.request.is_ajax():
                data = {
                    'code': 1,
                    'message': 'Успешно отправлено',
                }
                return JsonResponse(data)
            else:
                return response

But this is not entirely correct, but how to track each error and return it in the json response in order to process it and highlight the field through js. Who makes the bikes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VadimChin, 2016-11-04
@Romua1d

def ajax_errors(form):
    return {f: e.get_json_data(False) for f, e in
            form.errors.items()}
...
data = ajax_errors(form)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question