Archive for the 'Python' Category

A simple Django life stream

After reading Ryan Bergs' "The basics of creating a tumblelog with Django" (part1) and (part2), I realized that I wanted a similar tumblog/life stream but I didn't want to have to go through all the work of saving those objects to the database. After all, isn't all that data already stored in their respective systems. And since I am using FriendFeed, which is again duplicating all that data, I don't want to be duplicating it yet another time.

That's when the light bulb went off. Using the FriendFeed API and a bit of caching I can pull in my lifestream from FriendFeed using only a custom tag. So I came up with what I call lifefeed

Just add "lifefeed" to your installed apps and you can now do this from any template

{% load lifefeed %}{% load cache %}
{% cache 900 friendfeed %}
	{% lifefeed "YOUR FRIEND FEED USERNAME" %}
{% endcache %}
You can use the default friendfeed.html template that comes with lifefeed or use your own. You will most definitely want to use your own CSS to style the items since I am no CSS guru.

lifefeed is very simple right now but I would like to add more to it. Like

  • Consolidate duplicate twitter/pownce/brightkite posts
  • Display FriendFeed comments

To see an example of lifefeed in action check the sidebar on this page, you may have to scroll down a bit.

So what do you think?

Technorati Tags:

Intense Debate Import Hack

Recently I wanted to try out the Intense Debate commenting system on this blog. I didn't want to lose all the comments that I had already and Intense Debate only supports importing comments from Blogger, etc but not custom blog software. Since I wrote this blog using the Django framework using django.contrib.comments I needed to come up with my own solution.

It only took one Tamper Data request to see how an anonymous comment was posted into the Intense Debate system. A few minutes later I had a script to import my old comments into Intense Debate.

intenseDebate.py

import intenseDebate
intenseDebate.postComment(blogpostid="", acctid="", anonName="", anonEmail="", \
    anonURL="", comment="")

  • blogpostid is the unique Intense Debate postId. You can find this easily on any Intense Debate powered page using the firebug dom tab. The key to look for is "IDCommentScript".
  • acctid is your Intense Debate accountId. This can also be found using the firebug dom tab. The key to look for is "IDWUserWidget.acctid"
  • anonName is the name of the commenter
  • anonEmail is the commenters email address
  • anonURL is the commenters web address
  • comment is the text of the comment

This method of importing comments does have it's problems.

  1. Manual process to get the blogpostid.
  2. No way of getting the Date/Time into Intense Debate.
But it's better than no comments at all.

Footnote: I don't have a problem with Django comments, especially when paired with django-comment-utils, I just wanted to give Intense Debate a try.

Technorati Tags:

Django server side file selector

Note: This is no longer valid. You can now use the meta.FilePathField that is built into Django like this

fieldName = meta.FilePathField(path='/path/to/files', match='re_string', recursive=True)
I keep coming up with things that I think Django should have built in, but then end up being super easy to implement with just a few lines of code in the model. The TinyMCE editor was a good example of this, and it happened again with what I call a server side file selector. A project I am working on requires the admin user to select a video file to be associated with a message. I don't want users trying to upload very large video files over a HTTP POST, so they are manually uploaded to a directory via FTP. Initially the admin users had to manually type in the file location to a charField, but that just sucks. So I thought "Wouldn't it be great if I could do something like
videoUrl = meta.ServerFileField('/home/user/video')
and Django would automatically create a select field with all the files from that dir as options." After an hour of looking through core.py and formfields.py it dawned on me that I could just do this in the model. So here it is.
from django.core import meta
import os

videoDir = '/home/jay/video'
files = os.listdir(videoDir)
theList = []
for f in files:
	if os.path.isfile(os.path.join(videoDir,f)):
		theList.append(tuple([os.path.join(videoDir,f), f]))
videoChoices = tuple(theList)

class Message(meta.Model):
    def __repr__(self):
        return self.name
    
    title = meta.CharField(maxlength=200)
    video = meta.CharField(maxlength=200, help_text='Select the video', choices=videoChoices ,blank=True)
...
I had forgotten that Django can produce a select field if you just pass the meta.CharField a tuple of choices. No screenshot of this one since Gimp seems to have a hard time taking a screenshot of a HTML Select box

Technorati Tags:

Django and Xinha

After I posted about Django and TinyMce someone on IRC mentioned Xinha. I had not heard of or used Xinha before, so I thought I would give it a shot. Xinha has some really nice features that are not found in TinyMce, however I was a little bit disappointed at the extra configuration that Xinha required. TinyMce also just seemed a bit more polished.

Note that in order to get this to work I had to specify to Xinha the id's of the textarea's that I wanted to be wysiwyg editors. TinyMce was much more flexible in that it can convert every textarea on the page to a wysiwyg editro

I installed Xinha into my /home/skabber/public_html/javascript/xinha directory and then made symlink into the django/conf/admin_media/js directory.

Inside the xinha directory you will need to create 2 .js files

init.js will hold the follwoing

_editor_url  = "/media/js/xinha/";
_editor_lang = "en";
Note that _editor_url should be the location where Xinha is installed

description.js should contain the follwoing

 xinha_editors = null;
    xinha_init    = null;
    xinha_config  = null;
    xinha_plugins = null;

    // This contains the names of textareas we will make into Xinha editors
    xinha_init = xinha_init ? xinha_init : function()
    {
      xinha_plugins = xinha_plugins ? xinha_plugins :
      [
       'CharacterMap',
       'ContextMenu',
       'FullScreen',
       'ListType',
       'SpellChecker',
       'Stylist',
       'SuperClean',
       'TableOperations'
      ];
             // THIS BIT OF JAVASCRIPT LOADS THE PLUGINS, NO TOUCHING  :)
             if(!HTMLArea.loadPlugins(xinha_plugins, xinha_init)) return;

      xinha_editors = xinha_editors ? xinha_editors :
      [
        'id_description'
      ];

       xinha_config = xinha_config ? xinha_config() : new HTMLArea.Config();

      xinha_editors   = HTMLArea.makeEditors(xinha_editors, xinha_config, xinha_plugins);

      HTMLArea.startEditors(xinha_editors);
    }

    window.onload = xinha_init;

Now we are ready to edit our Django model. Just like in the TinyMce example use the js param of the meta.Admin to pass in 3 javascript files.

js = ('/media/js/xinha/init.js','/media/js/xinha/htmlarea.js','/media/js/xinha/description.js'),

Once that is done, log into the Django admin and add/edit one of your objects to see the Xinha editor.

These instructions only convert meta.TextField's with the name 'description' aka meta.TextField('description'), To change a field of a different id, modify the xinha_editors in the description.js and probably change that files name.

Technorati Tags:

Django on Dreamhost

After lots of googleing and some late night IRC chats I have Django installed and fully working on Dreamhost. The full how to is posted on the Dreamhost Wiki

Technorati Tags:

Django and TinyMce

I have been experimenting with the Django web framework for the past few days and it is great. It is easy to learn, and what it produces from the amount of code you input is staggaring.

One thing I did find lacking was lack of a wysisyg input field. meta.TextField works great but sometimes users need a little more. At first I wanted to create a meta.HtmlField but after some more thought you can achieve the same results with a meta.TextField and the admin.js param.

Before I get into the code here is a screenshot of what we will achieve. Django with TinyMce

Here's how:

First you will need to download the TinyMce code from http://tinymce.moxiecode.com/download.php Extract that to somewhere on your system. I used /Users/jay/Sites/javascript

Next you will need to link the TinyMce code into the Django media directory

ln -s /Users/jay/javascript/tinymce/jscripts/tiny_mce /Users/jay/python/django/trunk/django/conf/admin_media/js/tiny_mce

Your django may be in another dir.

To test that the tiny_mce is in the correct place, fire up the django server

djang-admin.py runserver --settings=myproject.settings.admin
and browse to http://127.0.0.1/media/js/tiny_mce/tiny_mce.js If you see a javascript file the you are on the right track.

Now create a textareas.js file in the tiny_mce dir and fill it with this.

tinyMCE.init({
	mode : "textareas",
        theme : "default"
});

Now we need to edit the model that we want to use TinyMce.

fields = (
        meta.CharField('title','title',maxlength=200),
        meta.TextField('description','description'),
        meta.CharField('location','location',maxlength=200)
    )
    
    admin = meta.Admin(
    		fields = (
    			(None, {'fields': ('title','description','location')}),
    		),
            js = ('/media/js/tiny_mce/tiny_mce.js','/media/js/tiny_mce/textareas.js'),
    )

Notice the "js" param in the admin section. This tells Django to load those javascript files on the add/edit page for this model.

If you have done all this correctly you should see the TinyMce editor for all the meta.TextField's in your model.

For more info on TinyMce, including how to tailor it to your needs go to http://tinymce.moxiecode.com/

Some people may not want to use TinyMce, but the same principals should apply to many wysiwyg editors. I may do another howto using the xinha editor, since someone has aked for that.

Technorati Tags:

Upcoming.org Python Module

I have just released a Python module for the Upcoming.org API. You can find it here. If you use it, please send all bugs, suggestions, patches to jay@socialistsoftware.com

Technorati Tags:

Upcoming.org Modules

Python Download 0.1 Example import Upcoming u = Upcoming.Upcoming('username', 'password', 'key') events = u.searchForEvents('Shins') for e in events: print e.id + ' : ' + e.name Output 14138 : The Shins 17314 : The Shins 17002 : The Shins Upcoming.py Pydoc ApiFilters.py Pydoc Java Download 0.3. Example import java.util.ArrayList; import com.socialistsoftware.upcoming.*; public class UpTest { public static void main(String[] args) { Upcoming up = new Upcoming("username", "password", "key"); ArrayList lists = up.getWatchlist(); for (int i = 0; i < lists.size(); i++){ Watchlist w = (Watchlist)lists.get(i); String id = w.getEventId(); Event e = (Event)up.getEventInfo(id).get(0); System.out.println(w.getEventId() + " : " + e.getName()); } } } Output 12447 : The Decemberists, Okkervill River 14135 : Q and not U 15001 : Fiery Furnaces, Dios Malos 14138 : The Shins 15517 : Electric Six and VHS or Beta 15516 : Built to Spill 15515 : Built to Spill 15737 : The Mars Volta 17074 : ... And you Will Know Us by the Trail of the Dead w/ International Noise Conspiracy and We Are Wolves 17078 : Spoon w/ The Clientele 18294 : Maroon 5 18543 : Nuggets vs Spurs 19323 : testEventName 19449 : WeedenFete The javadoc is here.

Technorati Tags:



Powered by Django.