class ProcessAddQuote(BaseCreateView, JSONResponseMixin): """ View mixin used built-in view class BaseCreateView `https://docs.djangoproject.com/en/dev/ref/class-based-views/#django.views.generic.edit.BaseCreateView` And proposed json serialize mixin to serialize response, i.o we using AJAX in form displaying and processing. BaseCreateView are creates view form form data, every time new instance. This class using ModeFormMixin `https://docs.djangoproject.com/en/dev/ref/class-based-views/#django.views.generic.edit.ModelFormMixin` `https://docs.djangoproject.com/en/dev/ref/class-based-views/#django.views.generic.edit.ProcessFormView` which construct modelform view as usual and ProcessFormView which validate and process form. """ form_class = QuoteAdd def form_invalid(self, form): """ Collect errors for serializing. """ errors = {'errors':{}} for i in form.errors.keys(): errors['errors'][i] = form.errors[i].as_text() return self.render_json_to_response(errors) def convert_context_to_json(self, context): """ Method are serialze saved quote instance or form errors. We need to serialize errors too, to show user how to fill the form. """ print type(context) try: isinstance(context.__class__(), DictionaryType) except TypeError: raise TypeError('context object is not serializeble') else: isinstance(context.__class__(), models.Model) context = {'author': context.author, 'content': context.content} finally: return super(ProcessAddQuote, self).convert_context_to_json(context) def form_valid(self, form): """ If form is valid user field appoint to current user. Then save instance. Saved instance set to regrialize. """ self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() quote_obj = Quote.objects.get(id=self.object.id) return self.render_json_to_response(quote_obj)