Tuesday, December 20, 2011

Scribd documents on Your page ( API ) - Django / python


In Django to display your Scribd documents in your page , first you need to install scribd python package . To install it refer this link

after installing it in your views write this def (add url accordingly).
def scribd(request):
    extra_context = {}
    extra_context['formName'] = 'scribd'   
    data = []
    import scribd       
    scribd.api_key = '#Your api key'
    scribd.api_secret = '#Your secret key'
    api_user = scribd.api_user   
    all_documents = api_user.all()
    for ad in all_documents:       
        temp = []
        document = ad
        document.load()   
        attrsDict = document.get_attributes()               
        temp.append(document.get_scribd_url())
        temp.append(attrsDict['thumbnail_url'])
        temp.append(document.get_download_url())     
        data.append(temp)
       
    extra_context['data'] = data
    return render_to_response('scribd.html', extra_context,
 context_instance=RequestContext(request))

In your scribd.html file............

My Documents on scribd:
< table border='1' >  
   {% for d in data %}               
        < tr>   
            < td width='82px'><a href='{{d.0}}'
 style='color:blue;font-weight: normal;'>
Doc {{forloop.counter}}:</a></td>
            <td><img width='' src='{{d.1}}' 
alt='doc{{forloop.counter}}'/>
</td>
            <td><a href='{{d.2}}' style='color:blue;
font-weight: normal;'>
Download doc {{forloop.counter}}
</a></td>
        </tr>       
   {% endfor %}
   </table> 

Live Demo
http://coderpriyu.alwaysdata.net/scribd/


Thats it....................

Tuesday, December 6, 2011

Database Connection Pool Solution for Django + Mysql


The solution:

An alternative DATABASE_ENGINE for django that leverages core django mysql code with minimal overlap and sqlalchemy for connection pooling. Also, a pretty ‘DRY’ stub to mix in your own pooling if desired, or adapt to use postgres instead of mysql.

1. Install sqlalchemy library: http://www.sqlalchemy.org/download.html
I used “Latest 0.5? myself.
2. Grab: mysql_pool.tgz

3. Make mysql_pool reachable by your project
3a. Unpack in your python’s “site-packages” directory
3b. Or: unpack somewhere in your project directory, and edit the “base.py” file in mysql_pool to fix the import lines containing uw.udjango.db.engine to be the new location mysql_pool.

4. Edit your settings.py to change DATABASE_ENGINE
4a. If 3a, set to uw.udjango.db.engine.mysql_pool
4b. If 3b, set to yourproject.whatever.mysql_pool

5. Edit your settings.py to add these (required) tuning settings:
  DBPOOL_WAIT_TIMEOUT = 28800  # your mysql db’s server side inactive connection kill time
# discernable by ’show GLOBAL variables;’ in mysql, look for ‘wait_timeout’, changeable if desired
DBPOOL_SIZE = 20 # the maintained number of dbconnections, over this returned conns are destroyed
DBPOOL_MAX = 100 # the max allow connections, period
DBPOOL_INTERNAL_CONN_TIMEOUT = 10 # how long to wait for mysql to give you a connection

That should do it!

The explanation:

I’ve been reading up on the various was being proposed to make some kind of persistent connection re-use part of core django. The are a couple of options I like, especially having a core database engine choice of sqlalchemy. A lot of implications there though, and I didn’t want to tackle them all.

At first I figured I’d write my own, and stubbed out the code to do that. Since I’m using mysql, I copied it’s engine tree in django.db.backends into my project and began working on it. Quickly I realized I didn’t want to rewrite, or maintain duplicates of, the whole tree. I only cared about two calls really: self.connection = Database.connect() and self.connection.close(). Modifying those would be a way to plug in pooling of my own. Also, in the process I looked to SQLAlchemy’s pool code as an example of Python implementation, and it seemed pretty good. Eventually I’d like to add some more subtlety to the pool grow/shrink strategy.

I started riffing on the solution described on Ed Menendez’s site, and merging in some of my ideas to make it more DRY.

Basically, all the classes in mysql_pool use class naming tricks to extend-without-modification and assume the identity and characteristics of the core mysql engine. That means there is no code in mysql_pool to maintain other than the “base.py” file, and even that one is able to use the same short cut for most of its classes, the exception being DatabaseWrapper, which is updated to use SQLAlchemy’s pool.

Also, I added settings.py level control of SQLAlchemy’s QueuePool, which is the pool type mysql_pool is forced to use.

Other links of note on related topics:

Proposal: user-friendly API for multi-database support

Monday, December 5, 2011

Django: How to add Google +1 button to your website.



What is Google +1 button?

It's new Google social button. It's much similar to Facebook "Like" button. While available during one month it earned popularity that could compete with Facebook's social button. Corporation of Good knows what to do, so you probably want to have one on your website inline with Facebook's Like...

Add Google +1 button to your site:

- Open http://www.google.com/webmasters/+1/button/index.html and generate own button for your website.

Google proposes HTML code like this:

<html>
  <head>
    <title>+1 demo: Basic page</title>
    <link rel="canonical" href="http://www.example.com" />
    <script type="text/javascript" src="https://apis.google.com/js/plusone.js">
    </script>
  </head>
  <body>
    <g:plusone></g:plusone>
  </body>
</html>

It's quite simple, as you can see. And that's much pretty it. Oh no wait...

- Add some variable to your template like "google_target_url" like this:


#pass variable to template with google +1 target url
return render_to_response("template.html", 
                         {"google_target_url":google_target_url,})

Finally you can add property "href" (similar to common a href=" " pattern) to target +1 action to custom url. In general you can now generate page with multiple +1 buttons on it. For e.g.: one button under one blogpost or image...

<g:plusone href="http://www.example.com/custom_page1/" size="standard" count="false"></g:plusone>


Django - compressing CSS/JS files with django-compressor



There are 2 main usual tasks with web project's deployment and about .css and .js files.

First one - size minimization. But there are lot's of utilities helping you to compress CSS files. Delete unused spaces, comments and so on... Second one - Version control. For e. g. When you've updated the script on your deployment server, but user's browser uses old one until user manually hits 'Refresh'.

That's where Static files compressor comes in to mind.



Upon selecting among available one's found top "google" results:
- django-compress
- django-compressor
- webassets

Project uses 'django.contrib.staticfiles', so django-compress was not compatible... It does not support Django's static files gently. Webassets s a good lib. but project has a huge amount of different static. Maybe it's ok for e small project, but when you need to specify/change a 100's javascript in python module for certain templates... Nothing good comes in mind. And imho TEMPLATES... That's where thing's like those should live.

So Django-compressor was chosen using those criteria. And, to mention, project is actively developed, supported and documented. Anyway adding it to your django project is quite simple, as most good apps.

What it does, it turns this:

<script type="text/javascript" src="{{ MEDIA_URL }}public/js
/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}banners/js/
jquery.cycle.all.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}js/gb/greybox.js"
></script>
<script type="text/javascript">jQuery.browser.msie6 = 
jQuery.browser.msie &&  parseInt(jQuery.browser.version) 
== 6 &&  
!window["XMLHttpRequest"];
if (!jQuery.browser.msie6) {
 $(document).ready(function(){
   $("div#body_wrapper").wrap('<div id="body_wrapper_shadow_right"
><div id="body_wrapper_shadow_left">'+
'</div></div>');
 });
</script>

Into this:

<script type="text/javascript" src="/static/CACHE/js/8dd1a2872443.js" 
charset="utf-8"></script>

The install is quite simple and you need to follow this manual.
Then configure it. Basically you hava all set for it to function. Except for me having a bit wired way of storing static files. I had to remap default COMPRESS_ROOT and COMPRESS_URL variables. It's quite easily done in settings.py. And it has lot's of other settings, that I did not require.

Anyhow this is it. Now you can wrap all of your code with handy templatetags that will do all the work for you. it may look somehow like this:

{% load compress %}

{% compress css %}
<link rel="stylesheet" href="/static/css/one.css" type="text/css" 
charset="utf-8">
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/static/css/two.css" type="text/css" 
charset="utf-8">
{% endcompress %}

or for .js files:

{% load compress %}

{% compress js %}
<script src="/static/js/one.js" type="text/javascript" charset="utf-8"
></script>
<script type="text/javascript" charset="utf-8">obj.value = "value"; 
</script>
{% endcompress %}

It will generate a custom .js/.css files with all of your compressed static at one file in your media/static dir that can be cashed. They will have links, like "/media/CACHE/css/105dsb963311.css"and put your newly generated script/style there. 

This is it. Use this in your projects. It economies your server's time/traffic and helps you to update scripts at all user's clients in their browsers when you deploy a new version.

Saturday, December 3, 2011

Django Tips & Features before getting Started



1. Dont hardcode MEDIA_ROOT and TEMPLATE_DIRS use 
        os.path.realpath(os.path.dirname)__file__)) 
hardcoding will cause problem while moving from dev->test->live

2. Dont hardcode static files in templates. use MEDIA_URL
EG: 
In future if you change your cdn, you will have to change it only in the settings
To get the context variable use django context processor. Its very easy to write and this makes MEDIA_URL and any other variable you like available across all the templates 

3. Use the url function to define the urls. Dont hardcode urls. Use reverse() in views.py and {% url %} tag in templates

4. Thirdparty app django-command-extension
This app is very useful. It gives some other useful commands  like
        -> shell_plus -  extension of shell. It will autoload all enabled django  models.
-> sqldiff - gives you the sql diff between the code and the DB
        -> show_urls - displays the url routes that are defined in the project
        -> graph_models - creates a GraphViz dot file 
        -> clean_pyc - removes all the pyc files    (Eclipse helois pydev makes it very easy...)
        -> reset_db - Resets a database

5. use pdb to debug django projects

6. dont copy paste html across templates. use {% extends %}, {% include %} and other builtin templatetags. write your own custom templatetags if necessary (they are very easy to write)

7. understand django middleware. Use this if you want to do some something before the request is processed / after the response is generated etc. - again they are very easy to write

8. use django forms - they are really really powerful 

9. use django test client for unit testing. It acts a dummy web browser. Its very useful to simulate GET and POST request



Hello world in Ruby on Rails step by step


I just started to learn ROR just because it is quite similar to Django


So, this is a step by step tutorial to getting over the first hurdle: Creating a “hello world” application in Ruby on Rails. This should work assuming you already have Rails 3 installed and running on your system:
  1. $ rails hello
  2. $ cd hello
  3. $ rails generate controller hello
  4. Open the file config/routes.rb. Almost at the bottom (line #57) is this line:
    # match ':controller(/:action(/:id(.:format)))'
    Remove the # in front so the line looks like:

    match ':controller(/:action(/:id(.:format)))'
  5. Create a file named index.html.erb in app/views/hello containing the text ‘Hello world’.
  6. $ rails server
  7. Navigate to http://localhost:3000/hello in your browser and be greeted by your friendly application: “Hello world”.
PS: http://localhost:3000/ is (still) a lot prettier “Hello world”-ish page.
PPS: Note that the Rails 3 example above actually has a step more than the Rails 1 ditto. This comes from the fact that Rails 3 doesn’t build a default route for you.
The code in this article has been verified with:
  • Ruby: 1.8.7
  • Rails: 3.0.0.beta

Ruby on Rails on windows with mysql


     
      This is basically what I do to install on Windows XP:

Wednesday, November 16, 2011

Django - Google maps on your page and display address in map entered in form




1) get gmapi , Django application for google map , from here http://code.google.com/p/django-gmapi/

2) copy gmapi folder to your project directory 

3) add gmapi to INSTALLED_APP and in urls.py add following two lines.
url(r'', include('gmapi.urls.media')), # Use for debugging only.
url(r'^$', 'main.views.index'),

4) in your main/views.py
def index(request):
    "intialize gmap with initial center location"
    gmap = maps.Map(opts = {
        'center': maps.LatLng(18, 72.5),
        'mapTypeId': maps.MapTypeId.ROADMAP,
        'zoom': 3,
        'mapTypeControlOptions': {
            'style': maps.MapTypeControlStyle.DROPDOWN_MENU
        },
    })
    """ This is my location  """
    xyam = 23   # longitude
    yyam = 72.5 # latitude
    """  for display marker on my location """
    marker = maps.Marker(opts = {
        'map': gmap,
        'position': maps.LatLng(xyam, yyam),
    })
    maps.event.addListener(marker, 'mouseover', 'myobj.markerOver')
    maps.event.addListener(marker, 'mouseout', 'myobj.markerOut')
    info = maps.InfoWindow({
        'content': "Priyank's location",
        'disableAutoPan': True
    })
    info.open(gmap, marker)
    
    """ to get address and display result on maps """
    if request.method == 'POST':
         from gmapi.maps import Geocoder
         geocoder = Geocoder()
         address = request.POST.get('address')
         results, status_code = geocoder.geocode({'address': address })
         if results:
             for r in results:
                 result = r
                 #print "location====",result['geometry']['location']
                 lat, lng = result['geometry']['location']['arg']
                 xyam = lat
                 yyam = lng

                 """ This markers are for search results """
                 marker1 = maps.Marker(opts = {
                 'map': gmap,
                 'position': maps.LatLng(xyam, yyam),
                 })
                 maps.event.addListener(marker1, 'mouseover', 'myobj.markerOver')
                 maps.event.addListener(marker1, 'mouseout', 'myobj.markerOut')
                 info = maps.InfoWindow({
                     'content': "Searched result",
                     'disableAutoPan': True
                 })
                 info.open(gmap, marker1)

    extra_context = {}
    extra_context['form'] = MapForm(initial={'map': gmap})
    return render_to_response('index.html', extra_context, context_instance=RequestContext(request))
5) in your index.html  put this line....
{{ form.map }}
{{ form.media.js }}

 < script type="text/javascript" >
    window.myobj = {
         markerOver: function() { this.openInfoWindow(); },
         markerOut: function() { this.closeInfoWindow(); }
    };
</script>

<form action='' method='post'>
         {% csrf_token %}
         Address:<input type='text' name='address'/>
         <input type='submit' value='Get location'/>
</form>
6) here is live example.......http://coderpriyu.alwaysdata.net

7) thats it . stay tune with blog , i w'll post shortly about how to display your live location in your page with google latitude api..

8) question ??.............comment it ...

Friday, November 4, 2011

Guide to Create Web service using JAVA and Apache Axis2 using Eclipse With Screen shot

Web services are application components which communicate using open protocols. Using Web Services we can publish our application's functions to everyone. This tutorial provides step by step instructions to develop Web Services using Axis2 Web Services / SOAP / WSDL engine and Eclipse IDE. Let's start.

Here is the step by step guide...........Click here



Tuesday, October 25, 2011

Django with solr - Now you are true web-dev



Apache Solr is an extremely powerful, enterprise level search engine, and can be used to store billions of records. For anyone with experience in MySql, you will understand how query time starts to degrade after reaching around 1,000,000 rows for any given table. After doing tons of research to try to find an alternative method for a quick and reliable search database, I stumbled upon the Apache Solr Project. The general consensus about Apache Solr is that it’s lightning fast, and after using it for a recent project I will definitely agree to this.

So this should be great news for a web developer who is looking for such a solution. Just go to the Apache Solr website, download and install the software, and you’re set right? Wrong! To give you a fair warning, the integration of Apache Solr onto your web server is a complete project in itself. The reason it’s so difficult is because of the lack of quality information online, so I’d like to share my knowledge to all you Apache Solr Noobs so you don’t have to rip your hair out your skull. If I can save just one hair follicle from this guide, then I’ve done my job. For women with mustaches, you may not want to continue reading as you may want to lose some facial hair.




The Downloads

Before I get started, I should let everyone know that this guide is mainly for Windows XP users, although there is a slight variation to the steps for anyone using the new Windows 7.

1. Download Xampp For Windows, Basic Package. http://www.apachefriends.org/en/xampp-windows.html

2. Download Tomcat Add-on. Tomcat is a java server and because Solr is run on Java getting Tomcat is necessary.

3. Download Java JDK http://java.sun.com/javase/downloads/index.jsp

4. Download Apache Solr from one of the mirrors. I got version 1.4.0 but I believe any version will do. http://www.proxytracker.com/apache/lucene/solr/

5. Download the Solr PHP Client. http://code.google.com/p/solr-php-client/




The Installation

1. Install Xampp, and follow the instructions.

2. Install Tomcat, and follow the instructions.

3. Install the latest java JDk.

4. There should now be a folder called /xampp in your C Drive. Enter the xampp folder and find the ‘xampp-control’ application, and start it.



5. Place a check mark for the Svc for Apache, MySQL, and Tomcat. This is so you install these applications as windows services.



6. Click the ‘SCM’ button and you should get a Windows Service Window.



7. Find the Apache Tomcat Service, then Right click it and go to ‘Properties’. Here you will set the Startup Type to Automatic, and close the properties window. We want Tomcat to start every time Windows boots up.




8. Now highlight Apache Tomcat in the Services Window, and click the option to Stop the Service if it’s not already Stopped. Tomcat has to be disabled for the next few steps.



9. Extract Apache Solr, then go into the /dist folder. There should be a file called apache-solr-1.4.0.war, copy this file.



10. Now find a folder in C:/xampp/tomcat/webapps/ and copy the apache-solr-1.4.0.war file into this folder. Rename apache-solr-1.4.0.war to solr.war.



11. Go back to the extracted Apache Solr folder and go to /example/solr/ then copy these files.



12. Create a New directory in C:/xampp/ called /solr/. You will now paste the /example/solr/ files into this directory.



13. Now find C:/xampp/tomcat/bin/tomcat6w, click on the Java Tab, and copy the command “-Dsolr.solr.home=C:xamppsolr” into the Java Options section.



14. Now go back to the Windows Services Window, and start Apache Tomcat.

15. Open up a browser and type “http://localhost:8080/solr/admin/” into the browser to confirm a successful installation of Apache Solr. You should see the Apache Solr Administrative Screen, if you see a bunch of error codes then you messed up. You might want to consider uninstalling everything, then start over and follow directions more carefully next time.






Python libraries to access Solr

Python API

There is a simple client API as part of the Solr repository: http://svn.apache.org/viewvc/lucene/solr/tags/release-1.2.0/client/python/

Note: As of version 1.3, Solr no longer comes bundled with a Python client. The existing client was not sufficiently maintained or tested as development of Solr progressed, and committers felt that the code was not up to our usual high standards of release.

solrpy

solrpy is available at The Python Package Index so you should be able to:

easy_install solrpy

Or you can check out the source code and:

python setup.py install

PySolr

There is a independent "pysolr" project available ... http://code.google.com/p/pysolr/

And Python Solr, And enhanced version of pysolr that supports pagination and batch operations.

insol

Another independent Solr API, focused on easy of use in large scale production enviroments, clean and fast, still in development

http://github.com/mdomans/insol

sunburnt

Sunburnt is an actively-developed Solr library, both for inserting and querying documents. Its development has aimed particularly at making the Solr API accessible in a Pythonic style. Sunburnt is in active use on several internet-scale sites.

http://pypi.python.org/pypi/sunburnt

http://github.com/tow/sunburnt

Using Solr's Python output

Solr has an optional Python response format that extends its JSON output in the following ways to allow the response to be safely eval'd by Python's interpreter:

  • true and false changed to True and False
  • Python unicode strings used where needed
  • ASCII output (with unicode escapes) for less error-prone interoperability
  • newlines escaped
  • null changed to None

Here is a simple example of how one may query Solr using the Python response format:

from urllib2 import *
conn = urlopen('http://localhost:8983/solr/select?q=iPod&wt=python')
rsp = eval( conn.read() )

print "number of matches=", rsp['response']['numFound']

#print out the name field for each returned document
for doc in rsp['response']['docs']:
  print 'name field =', doc['name']

With Python 2.6 you can use the literal_eval function instead of eval. This only evaluates "safe" syntax for the built-in data types and not any executable code:

import ast
rsp = ast.literal_eval(conn.read())

Using normal JSON

Using eval is generally considered bad form and dangerous in Python. In theory if you trust the remote server it is okay, but if something goes wrong it means someone can run arbitrary code on your server (attacking eval is very easy).

It would be better to use a Python JSON library like simplejson. It would look like:

from urllib2 import *
import simplejson
conn = urlopen('http://localhost:8983/solr/select?q=iPod&wt=json')
rsp = simplejson.load(conn)
...

Safer, and as you can see, easy.


For Django developers ...... Use Django Application

Haystack for Django

Haystack provides modular search for Django. It features a unified, familiar API that allows you to plug in different search backends (such as Solr, Whoosh, Xapian, etc.) without having to modify your code.

http://docs.haystacksearch.org/dev/toc.html

Ubuntu users follow this link to install solr and access it through haystack

http://yuji.wordpress.com/2011/08/18/installing-solr-and-django-haystack-on-ubuntu-with-openjdk/

Wednesday, October 19, 2011

Comet with Django and Ajax push engine ( APE )

Recently I have implemented APE in my project . Before APE i was using continuous ajax call that is obviously very bad idea... in APE each user has its own pubid , channel , sessId . Channel is used for sending message to another user or vice-versa....

 Here....I just slapped together a really basic message posting app. Just a message with a name and a timestamp.


# Here's the model:
class Message(models.Model):
    msg = models.TextField('Message')
    timestamp = models.DateTimeField('Timestamp', auto_now_add=True)
    posted_by = models.CharField(max_length=50)
# And here's the view:
def show_messages(request):
    if request.method == 'POST':
        new_msg = Message(msg = request.POST['msg'],
                          posted_by = request.POST['posted_by'])
        new_msg.save()
    messages = Message.objects.all()
    return render_to_response('messages.html', {'messages': messages})
And here’s the template:

<style type='text/css'>
    div.message {
        background: #DDDDDD;
        margin: 10px;
        padding: 10px;
    }
</style>
<div id="current_messages">
    {% for message in messages %}
    <div class="message">
        {{ message.msg }}<br />
        Posted by: <strong>{{ message.posted_by }}</strong><br />
        on: {{ message.timestamp }}
    </div>
    {% empty %}
        <div class="message">
            No Messages
        </div>
    {% endfor %}
</div>
<div id="new_message">
    <form id="msgform" method="post">
    <h2>Post a new message</h2>
    Your Name: <input name="posted_by" type="text" /><br />
    Your Message:<br />
    <textarea cols="50" rows="10" name="msg"></textarea><br />
    <input type="submit" value="Submit Message" />
    </form>
</div>

Ok, so that’s the basic setup… Pretty boring, right? If Sue submits a message, Bob has to refresh his page to see it. So, we’re going to add APE into the mix to update Bob right away. Getting APE up running it pretty easy, just follow the instructions over at the APE Wiki. We’ll be using APE’s inlinepush server module. Just for good measure we’ll be tossing some jQuery in as well.
So, the basic idea is we need to connect to a APE “channel” which we’ll use to receive updated messages. We’ll use jQuery to send the messages. So let’s start by using jQuery to submit the form, with the following script:

function append_message(data) {
    fields = data[0].fields;
    message_str = fields.msg + '\nPosted by: <strong>'
                         + fields.posted_by + '</strong> on: '
                         + fields.timestamp;
    new_div = $('<div />').addClass('message').html(message_str);
    $('div#current_messages').append(new_div);
}
$('#msgform').submit(function() {
    $.post('/ajaxsubmit',
            {posted_by: $("input[name='posted_by']").val(),
               msg: $("textarea[name='msg']").val()},
            append_message, 'json');
     //For brevity, we're just going to assume this always works
     $("textarea[name='msg']").val('');
     return false;
});

And here are the updated views:

def show_messages(request):
    messages = Message.objects.all()
    return render_to_response('messages.html', {'messages': messages})
def ajaxsubmit(request):
    new_msg = Message(msg = request.POST['msg'],
                      posted_by = request.POST['posted_by'])
    new_msg.save()
    jsonified_msg = serializers.serialize("json", [new_msg])
    # Again, we're just going to assume this always works
    return HttpResponse(jsonified_msg, mimetype='application/javascript')

And so with that, we can now submit messages without reloading the page. Any other users, however, would need to refresh to see the new messages. That’s where APE comes in. Here’s the APE client code (along with the updated append_message function):

var client = new APE.Client();
client.load();
client.addEvent('load', function() {
    posted_by = prompt('Your name?');
    client.core.start({"name": posted_by});
    $("input[name='posted_by']").val(posted_by);
});
client.addEvent('ready', function() {
    //Once APE is ready, join the messages channel and wait for new messages
    client.core.join('messages');
    client.onRaw('postmsg', function(raw, pipe) {
        append_message(raw.data);
    });
});
function append_message(data) {
    message_str = data.msg + '\nPosted by: <strong>'
                         + data.posted_by + '</strong> on: '
                         + data.timestamp;
    new_div = $('<div>').addClass('message').html(message_str);
    $('div#current_messages').append(new_div);
}

And here’s the updated view to send new posts to APE:

def ajaxsubmit(request):
    new_msg = Message(msg = request.POST['msg'],
                      posted_by = request.POST['posted_by'])
    new_msg.save()
    # Again, we're just going to assume this always works
    cmd = [{'cmd': 'inlinepush',
            'params': {
                'password': settings.APE_PASSWORD,
                'raw': 'postmsg',
                'channel': 'messages',
                'data': {
                    'msg': new_msg.msg,
                    'posted_by': new_msg.posted_by,
                    'timestamp': new_msg.timestamp
                }
            }
    }]
    url = settings.APE_SERVER + urllib2.quote(json.dumps(cmd))
    response = urllib2.urlopen(url)
    # Updating the message is handled by APE, so just return an empty 200
    return HttpResponse()
You’ll notice I’ve added two settings to settings.py:
APE_PASSWORD = 'testpasswd'
APE_SERVER = 'http://ape-test.local:6969/?'

And that’s all there is to it! Like I said earlier, this is a very incomplete application, and a lot of the “boilerplate” work is left as an exercise for the reader. It should be more than enough to get you on your way though. Perhaps in a later post I’ll move the APE update from inside the view to a post_save signal on the model itself. That’s for another time though… UPDATE: Well, another time is today. Check out this post about adding a signal handler.

Reference : http://www.alittletothewright.com/index.php/2010/01/comet-with-django-and-ape/

If any question or error then feel free to comment here........before that i would like to write some problems/guidelines/alternative solution  that i had used in my project.....

1)  Ready event not working when page refresh :
-> yes.........to get it working you have to use session to store each user .........OR ........without session u can append random no to name when calling client.core.start that will load new user each time .

2)  Implement chat...
-> To implement chat u need to register new channel for each user ...when somebody wants to chat he/she will send message to that channel using pipe.send method and the target user will check for new msg using client.onRaw method.......