Login

AjaxForm Base Classes

Author:
btaylordesign
Posted:
March 16, 2011
Language:
Python
Version:
1.2
Score:
3 (after 3 ratings)

These base form classes add a method to return error messages as HTML encoded as JSON from Django, optionally passing in an argument to strip tags out. The method can be called in your view after checking that your form is valid. There is a ModelForm and Form class to use depending on your needs.

The sample jQuery function will take the errors returned as json, loop over the errors and insert the error after each field. If you're using a form prefix, you'll need to add a hidden field to hold the value for the prefix.

The __all__ error(s), which are not bound to a field are appended to the end of the form, which you could easily reposition.

Happy coding!

 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from django import forms
from django.conf import settings
from django.template.defaultfilters import striptags


class AjaxBaseForm(forms.BaseForm):
    def errors_as_json(self, strip_tags=False):
        error_summary = {}
        errors = {}
        for error in self.errors.iteritems():
            errors.update({error[0] : unicode(striptags(error[1]) \
                if strip_tags else error[1])})
        error_summary.update({'errors' : errors })
        return error_summary


class AjaxModelForm(AjaxBaseForm, forms.ModelForm):
    """Ajax Form class for ModelForms"""


class AjaxForm(AjaxBaseForm, forms.Form):
    """Ajax Form class for Forms"""


Example Usage:

    #forms.py
    from my_app import AjaxForm

    class MyForm(AjaxForm):
        first_name = models.CharField(max_length=40)

    #views.py
    try:
        import json
    except ImportError:
        import simplejson

    from django.views.shortcuts import render_to_response

    from my_app.forms import MyForm

    def my_view(request):
        if request.method == 'GET':
            form = MyForm()
        else:
            form = MyForm(request.POST)
            if form.is_valid():
                response = {'success' : True}
            else:
                response = form.errors_as_json()
            return HttpResponse(json.dumps(response, ensure_ascii=False),
                mimetype='application/json')
        return render_to_response('my_template.html', {'form' : form})

Sample JavaScript implementation to handle json returned
using jQuery and the jQuery Form plugin. You'll need to add a hidden field
to your form to hold the value for the form prefix, if you're using one.

This example leverages the jQuery Form plugin:
http://www.malsup.com/jquery/form/

    jQuery(function($){
        var login_form = $('#login');
        login_form.ajaxForm({
            url : this.action,
            dataType : 'json',
            success : function(json)
            {
                if (json.errors != undefined)
                    process_form_errors(json, login_form)
                else
                    //do something if there aren't errors
            }
        }); 
    });

    function hide_form_errors()
    {
        $('.errorlist').remove();
    }

    function process_form_errors(json, form)
    {
        hide_form_errors();
        form.clearForm();
        errors = json.errors;
    
        if (errors.__all__ != undefined)
            form.append(errors.__all__);

        prefix = form.find(":hidden[name='prefix']").val();

        prefix == undefined ? prefix = '' : prefix = prefix + '-';
        for (field in errors)
            $('#id_' + prefix + field).after(errors[field]);
    }

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.