Class based view returns json serialized saved data or form errors.
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.