Code


Version 2 (modified by davidschein@…, 8 years ago) (diff)

--

Add spell checking to all the textarea elements on an admin page

Notice that, except for adding a reference to the GoogieSpell stylesheet, you do not have to mess with the admin tempates at all. Once you have done steps 1-5, you can repeat step 6 on any model you want spell checking. Obviously, you can be more selective in what you set spell checking up for by, for instance, getting elements by id instead of the textarea tag.

  1. Get GoogieSpell and stick it with your other static media.
  1. Add a url mapping, something like:
    urlpatterns += patterns('rise.catalog.spellcheck',
        (r'^spellcheck/$', 'spellcheck'), 
    )
    
  1. Create the view:
    from django.http import HttpResponse
    from django.utils import simplejson
    import httplib
    
    GOOGLE_URL = "www.google.com"
    
    def spellcheck(request):
        if request.method == 'POST':
            lang = request.GET.get("lang", "en")
            data = request.raw_post_data
            con = httplib.HTTPSConnection(GOOGLE_URL)
            con.request("POST", "/tbproxy/spell?lang=%s" % lang, data)
            response = con.getresponse()
            r_text = response.read()
            con.close()
            return HttpResponse(r_text, mimetype='text/javascript')
    
  1. Create a little javascript function that runs when the page loads (I am using MochiKit, too, which is where addLoadEvent and getElementsByTagAndClassName come from.) This function grabs all the textarea elements and hooks them up to GoogieSpell. In this example, this file is rise/js/spellcheck.js.
    addLoadEvent(function() {
            var elems = getElementsByTagAndClassName("textarea", null);
            for (var i = 0; i < elems.length; i++) {
                var elem = elems[i];
                var googie1 = new GoogieSpell("/site_media/googiespell/", "http://localhost/spellcheck/?lang=");
                googie1.decorateTextarea(elem.id);
            }
        }
    )
    
  1. Add the GoogieSpell stylesheet to base_site.html (or some template that will make sure it is loaded for the form in question):
    {% block extrastyle %}
    <link rel="stylesheet" type="text/css" href="/site_media/googiespell/googiespell.css" />
    {% endblock %}
    
  1. Hook it up by including the js attribute to the Admin class for your model, as in:
        class Admin:
            js = ['../MochiKit/MochiKit.js', 
                  '../googiespell/AJS.js', '../googiespell/googiespell.js', '../googiespell/cookiesupport.js', 
                  '../rise/js/spellcheck.js']