Class-based process form view.

 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

  1. Class-based view mixin for flatpages by schwuk 2 months, 3 weeks ago
  2. AjaxForm Base Classes by btaylordesign 2 years, 2 months ago
  3. Decorating class-based views by lqc 1 year, 3 months ago
  4. Allow separation of GET and POST implementations by agore 11 months, 1 week ago
  5. Middleware to resolve current URL to module and view by kuchin 2 years, 10 months ago

Comments

(Forgotten your password?)