Login

Class-based process form view.

Author:
I159
Posted:
December 5, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

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

  1. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 weeks, 4 days ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month ago
  3. Browser-native date input field by kytta 2 months, 2 weeks ago
  4. Generate and render HTML Table by LLyaudet 2 months, 3 weeks ago
  5. My firs Snippets by GutemaG 3 months ago

Comments

Please login first before commenting.