Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

pyjamaswithdjangoformsjsonrpc

supercheetah edited this page · 4 revisions

How to use JSON-RPC with Django Forms

Obtain jsonrpc.py from http://groups.google.com/group/pyjamas-dev/files place it in an appropriate location (in the root of the django app)

With the following as the Model:

class Question(models.Model):
    prompt = models.CharField(max_length=200)
    variable = models.CharField(max_length=200)
    def __unicode__(self):
        return self.prompt

It's possible to create form processors as JSONRPC functions, using FormProcessor, as follows:

from jsonrpc import FormProcessor

from django import forms

class SimpleForm(forms.Form):
    testfield = forms.CharField(max_length=5)
    intfield = forms.IntegerField(min_value=2, max_value=5)

from django.forms import ModelForm

class QuestionForm(ModelForm):
    class Meta:
        model = Question

processor = FormProcessor({'processsimpleform': SimpleForm,
                           'processquestionform': QuestionForm})

Next, add a line to urls.py urlpatterns:

  (r'^formservice/$', 'djangoapp.views.processor'),

Using the jsonrpclib by Matt Harrison - available from http://lkcl.net/jsonrpclib.tgz - it's possible to do tests as follows. adapt the URI to point to and match your specific project's django URLs:

#!/usr/bin/env python

f = jsonrpclib.ServerProxy("http://127.0.0.5/lib-wsgi/qnaire/formservice/",
                           verbose=0)
try:
    reply = f.processsimpleform({'testfield': "hello there", 'intfield': 100})
    print "reply:", reply['result']
except jsonrpclib.ProtocolError, e:
    print e, e.errcode, e.errmsg, e.message, e.args, e.response


try:
    reply = f.processsimpleform({'testfield': "ok", 'intfield': 2})
    print "reply:", reply['result']
except jsonrpclib.ProtocolError, e:
    print e, e.errcode, e.errmsg, e.message, e.args, e.response


try:
    reply = f.processquestionform({'variable': "fred", 'prompt': 'who is the greatest?'})
    print "reply:", reply['result']
except jsonrpclib.ProtocolError, e:
    print e, e.errcode, e.errmsg, e.message, e.args, e.response

See also

Something went wrong with that request. Please try again.