Tuesday, October 21, 2008

A Brief Pyjamas + Django Tutorial

Update: (June 19, 2009) Since the writing of this post, Pyjamas has been updated and the below code no longer works, though the principles discussed are still valid. The example code is now being maintained in the pyjamas Sourceforge repo, located here.


Intro:


Django is a web framework written in Python. Pyjamas is a Python port of the google web toolkit (written in Java). Pyjamas can be used with Django to create web applications.

In terms of an MVC framework, Django acts as the Model and Pyjamas acts as the Views and Controller.

The "Todo List" Application:

In this brief tutorial, we will create a very simple todo list. The primary purpose of this tutorial is to briefly demonstrate how to serve data with Django, how to create and display widgets with Pyjamas, and how to handle user events with Pyjamas.

Prerequesits:

Here is the software that is needed:
This tutorial will not go into how to install each of these components, nor their basic usage. Hopefully, some of them can be downloaded as packages for your linux distribution. One reader recommended that you have a fairly recent Django version. > 1.0 should work.

The Code:

pyjsDemo/urls.py:
from django.conf.urls.defaults import *
from django.conf import settings

urlpatterns = patterns('',
(r'^services/$', 'todo.views.service'),
(r'^site_media/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC}),
)

pyjsDemo/settings.py


# ADD THIS
import os
STATIC = str(os.path.join(os.path.dirname(__file__), 'media').replace('\\','/'))

# MODIFY THIS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'todo' # Or path to database file if using sqlite3.
DATABASE_USER = 'todo' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.

# MODIFY THIS
INSTALLED_APPS = (
'pyjsDemo.todo',
)

pyjsDemo/todo/models.py:

from django.db import models

class Todo(models.Model):
task = models.CharField(max_length=30)

def __unicode__(self):
return str(self.task)


pyjsDemo/todo/views.py:


from django.pimentech.network import *
from todo.models import Todo

service = JSONRPCService()

@jsonremote(service)
def getTasks (request):
return [(str(task),task.id) for task in Todo.objects.all()]


@jsonremote(service)
def addTask (request, taskFromJson):
t = Todo()
t.task = taskFromJson
t.save()
return getTasks(request)

@jsonremote(service)
def deleteTask (request,idFromJson):
t = Todo.objects.get(id=idFromJson)
t.delete()
return getTasks(request)


pyjsDemo/media/TodoApp.html:



See the download for this. It's short, but I can't figure out how to paste html into my blog. I'm lazy.



pyjsDemo/media/TodoApp.py:


from ui import Label, RootPanel, VerticalPanel, TextBox, KeyboardListener, ListBox
from JSONService import JSONProxy

class TodoApp:
def onModuleLoad(self):
self.remote = DataService()
panel = VerticalPanel()

self.todoTextBox = TextBox()
self.todoTextBox.addKeyboardListener(self)

self.todoList = ListBox()
self.todoList.setVisibleItemCount(7)
self.todoList.setWidth("200px")
self.todoList.addClickListener(self)

panel.add(Label("Add New Todo:"))
panel.add(self.todoTextBox)
panel.add(Label("Click to Remove:"))
panel.add(self.todoList)
RootPanel().add(panel)


def onKeyUp(self, sender, keyCode, modifiers):
pass

def onKeyDown(self, sender, keyCode, modifiers):
pass

def onKeyPress(self, sender, keyCode, modifiers):
"""
This functon handles the onKeyPress event, and will add the item in the text box to the list when the user presses the enter key. In the future, this method will also handle the auto complete feature.
"""
if keyCode == KeyboardListener.KEY_ENTER and sender == self.todoTextBox:
id = self.remote.addTask(sender.getText(),self)
sender.setText("")
if id<0: id =" self.remote.deleteTask(sender.getValue(sender.getSelectedIndex()),self)" method ="=" method ="=" method ="=">

pyjsDemo/media/build.sh

python ~/python/pyjamas-0.3/builder/build.py TodoApp.py



A very brief walk through of how to get this running:

Extract the demo:
  • tar -xvvzf pyjamasDjango.tar.gz
Create the db:
  • mysql -u root
  • > CREATE DATABASE todo;
  • > grant all privilages to todo.* to 'todo'@'localhost'; (or possibly > grant all on todo.* to 'todo'@'localhost';)
  • > exit;
Create the tables:
  • cd pyjsDemo
  • python manage.py syncdb
Build the javascript:
  • vim media/build.sh
  • (edit this so that it points to the build.py of pyjamas)
  • media/build.sh
Run the server:
  • python manage.py runserver
Test it out:
  • In your browser, goto: http://127.0.0.1:8000/site_media/output/TodoApp.html

Here are the demo source files:

36 comments:

mauro said...

I tried the demo
the db gets updated but the list is not shown on the page...
any idea?

OlsenUpdate said...

thank you so much for this great enlightment. I don't know what i'd do without you bro!

Jeff Bauer said...

Agree with mauro. New items get added to the database, but do not appear on the task list. onRemoteReponse is not invoked.

Another suggestion for this example would be to demo it with sqlite, rather than MySQL.

Dr. Mobeus said...

Works perfectly for me, using Pyjamas 0.4 and mySQL 5.1 and Django 1.02. I'm on WinXp SP3.
Just to update matters, if you are also on mySQl 5.1, the syntax has changed, so that you have to do:
CREATE USER todo.localhost
before granting rights. minor point, but it might stub a newbie :-)

I'm wondering if it's possible to use Pyjamas to interact with Dojo (or better still, 'wrap' dijit controls)... At the very least - as a stop gap - I might try using dojo controls on a DJango template, and the write the functions that are triggered by user events (e.g. clicking on a button) in pyjamas.

Unknown said...

Nice posting.

Wrote a similar one covering pyjs + appengine - http://amundblog.blogspot.com/2008/12/ajax-with-python-combining-pyjs-and.html

funkazio said...

Thanks!Interesting!

@ mauro and Jeff Bauer

The task list seems not to be updated because a Javascript error is fired when you don't have the "FireBug" plugin installed (all the "console.something()" instructions only work with this plugin). After you install that, the example works (at least for me) using mysql or sqlite3. However the task list is loaded only when you insert a task, and not at startup. (ok for me then, using. WinXPsp3, Python2.6, Django 1.1 pre-alpha SVN-9645, pyjamas-0.4, libcommonDjango).

Soulburner said...

To get the todolist populating on page load i added
"self.remote.getTasks(self)"
to the end of the onmoduleload function

was playing around with using this in an existing web app and i found you can use django templating to dynamically change the content and src directory in the base html file

simak said...

Hello. Nice source of info about pyjamas and Django, but I had some problems here: A blank page. Any I deas on how to debug it? Any log I could pay attention to?

Unknown said...

when i try the tutorial with pyjamas 0.5 i get this error :"Exception: file not found: JSONService.py" after buld.sh. to "upgrade" the tutorial for pyjamas 0.5sp1 we must change the import in TodoApp.py
in
from pyjamas.ui import Label, RootPanel, VerticalPanel, TextBox, KeyboardListener, ListBox
from pyjamas.JSONService import JSONProxy

hope this help.

Giancasa

Raketemensch said...
This comment has been removed by the author.
Raketemensch said...

The build.sh wasn't working for me for some reason, so I just manually called "pyjsbuild ToDoApp" and moved on to launching the server.

The app bombs for me though. Trying to enter text throws:

JavaScript Error: object is undefined at line number 2050. Please inform webmaster.

Clicking the (empty) task list throws:

JavaScript Error: elem is null at line number 4346. Please inform webmaster.

I have tried installing FireBug as mentioned above, but still no joy. I'm running Firefox 3.0.13 on OS Leopard.

Bhanu Sree said...


Thank you for sharing wonderful information with us to get some idea about that content.
Django Online Courses
Django Training in Hyderabad
Python Django Online Training
Python Django Training in Hyderabad

Ananya said...

Thanks for shairng.
Online Machine Learning training in Pallikranai Chennai
Online Data science training in Pallikaranai
Online Python Training in Pallikaranai chennai
Online Bigdata training in Pallikaranai chennai
online Spark with ML training in Pallikaranai chennai

Bhanu Sree said...

It is amazing to visit your site. Thanks for sharing this information, this is useful to me...

Django Online Courses
Django Training in Hyderabad
Python Django Online Training
Python Django Training in Hyderabad

Ankita Kumari said...

Thank you for writing this informative post. Looking forward to read more.
Best Web Design and Development Company

ajith said...

thank you for the information
angular js course in chennai

angular course in chennai

angular js online course in chennai

angular js course in bangalore

angular js course in hyderabad

angular js course in coimbatore

angular js course

angular js online course

Rohit said...

It was reaaly wonderful reading your article. # BOOST Your GOOGLE RANKING.It’s Your Time To Be On #1st Page
Our Motive is not just to create links but to get them indexed as will
Increase Domain Authority (DA).We’re on a mission to increase DA PA of your domain
High Quality Backlink Building Service
1000 Backlink at cheapest
50 High Quality Backlinks for just 50 INR
2000 Backlink at cheapest
5000 Backlink at cheapest

Thakur98 said...

We are used to the fact that we know only religious and public holidays and celebrate only them.Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder Iamlinkfeeder

Tec said...

NDUW is a labor registration portal created by the Labor Department, Government of india. The registration of the unorganized workers (working class) of the state takes place on this portal.

Unknown said...

jan adhar card very usefull in rajsthan govt. All Process in Download See Now

Linkfeeder said...

Tired of sharing long, nasty URLs? This app immediately shortens URLsLinkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0 Linkfeeder3.0

lakshmibhucynix said...

Thank you ever so for you article. Really Cool.
data science course in hyderabad
data science training in hyderabad

SEO LOCAL said...

cita dni alcoy
cita previa dni plasencia
cita dni fuenlabrada
cita dni
cita dni quintilla del olmo
cita dni calanas
cita dni puerto del rosario

Techystick said...

world777 betting
modular lab furniture
class 9 tuition classes in gurgaon
lab cabinet manufacturer
cloudkeeda
what is azure
azure free account
azure data factory
Azure Data Factory Interview Questions and Answers

deunopostehoje said...

All hosting info
Click
Click ther and hear
cheap wordpress hosting
Click ther and hear
best vps hosting
Click ther and hear
best vps hosting
Click ther and hear
free wordpress hosting reddit
Click ther and hear
Click

MCQ SOLUTIONS said...

Click :-https://cattlepetsdog.blogspot.com/
Rade australian cattle dog wesen.
Click:-https://cattlepetsdog.blogspot.com/2022/01/australian-cattle-dog-wesen.html

Aakash Shahakar said...

Step Up sip calculator or Top up calculator gives you the future value of your SIP investments which increases periodically by a given percentage.

Sruthi Karan said...

I really appreciate your valuable efforts and it was very helpful for me. Thank you so much...!
Sole custody Virginia
Protective Order Virginia

Core creator said...

Best lifetime memorable gift for your loving one. A mosaic is an image made up of several images in a single photo. It turns out that one picture is made up of several smaller pictures. Our designer team designs your photos beautifully and colorfully. Hundreds of memorable photos are displayed in one photo.
Click here

Core creator said...

Best lifetime memorable gift for your loving one. A mosaic is an image made up of several images in a single photo. It turns out that one picture is made up of several smaller pictures. Our designer team designs your photos beautifully and colorfully. Hundreds of memorable photos are displayed in one photo. You can gift hundreds of memories together by gifting a Mosaic Image. When your loved one sees photos, they will love it! That’s why mosaic photo designs are one of the best gifts you can give because they hold precious memories.

Click here

Manish said...
This comment has been removed by the author.
Core creator said...

Liman Restaurant


The Liman Restaurant means port in the Turkish language, however the restaurant opens its doors to all aspects of the Mediterranean kitchen. The kitchen will be mostly focused on Mediterranean food.

tech2 said...

Edius Pro 9 Free Download Latest Version for Windows. It is full offline installer standalone setup of Edius Pro 9 Free Download.Edius Pro 9 Software Free Download For Pc

Blck Luxury car said...

Shri Mintu's Art forayed into the online furniture space as https://shrimintus.com/
to offer value-for-money furniture made of sheesham wood to Indian consumers.
The manufacturer and online seller provides finished
as well as customised products to buyers.
Enjoy a wide variety of traditional and modern living room furniture with shri Mintus Art.

Wooden furniture

Anonymous said...

WhyDonate is een wereldwijd fondsenwervingsplatform dat doelen op een efficiënte, relevante en plezierige manier verbindt met donateurs.
Crowdfunding platforms zoals WhyDonate zijn nu één van de meest betrouwbare manieren waar mensen van overal ter wereld geld voor elk doel kunnen inzamelen.


100 Inzamelingsactie Ideeën die u Efficiënt kunnen Helpen Geld in te zamelen voor uw Doel

Fundraising Ideas

Appwars Technologies Pvt. Ltd. said...

https://dsbyprateekg.blogspot.com/p/python-basics-lists.html

Pyjamas