Django Admin interface for a Blog in 5 mins

It’s so cool with Django:

from django.db import models
from django.contrib.auth.models import User

class Tag(models.Model):
    name = models.CharField(maxlength=200, core=True)

    class Admin:
        ordering = ['name']   

    def __str__(self):
        return self.name

PUBLICATION_CHOICES = (
    ('Draft', 'Draft'),
    ('Published', 'Published'),
)

class Post(models.Model):
    author = models.ForeignKey(User)
    title = models.CharField(maxlength=200)
    summary = models.TextField()
    body = models.TextField()
    created = models.DateTimeField(default=models.LazyDate())
    last_modified = models.DateTimeField(auto_now=True)
    enable_comments = models.BooleanField(default=True)
    tags = models.ManyToManyField(Tag)
    publication = models.CharField(maxlength=32, choices=PUBLICATION_CHOICES, radio_admin=True, default='Published')

    class Admin:
        ordering = ['-created']
        search_fields = ['title']
        list_display = ('title','author', 'created')
        list_filter = ('created','last_modified','enable_comments','publication', 'tags')

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post)
    name = models.CharField(maxlength=100)
    email = models.EmailField()
    website = models.CharField(maxlength=200, blank=True, null=True)
    comment = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)

    class Admin:
        ordering = ['-created']
        search_fields = ['name']
        list_display = ('post','name', 'created')
        list_filter = ('created','last_modified')

    def __str__(self):
        return self.name

Crazy load!

The picture says all ;)

Crazy load

Busy days

I’m alive!
Besides of the crazy days at my work, i’ve been working in a personal project that will be released in a couple of weeks.

NOTE: Python rules ;)

Zend Framework Released

The much awaited Zend Framework was released!

ActiveRecord PHP implementation Part I

ActiveRecord UML

This is the first part of an attempt to implement the ActiveRecord design pattern in PHP.
This first implementation is very simple but will open doors for more advanced stuff, like foreign keys mapping(automatic or manually) or integration with Model, View and Controller components, in this case with the generation of PHP classes or objects.

Approach: A row in a database table or view is wrapped into a class, thus an object instance is tied to a single row in the database.

Imagine this table(person):

+-------------+---------------------+
| Field       | Type                |
+-------------+---------------------+
| id          | bigint(20) unsigned |
| name        | varchar(100)        |
| email       | varchar(150)        |
| last_update | datetime            |
+-------------+---------------------+

With this records:

+----+----------+---------------+---------------------+
| id | name     | email         | last_update         |
+----+----------+---------------+---------------------+
|  1 | Nuno     | nuno@xxx.xxx  | 2005-11-06 20:39:08 |
+----+----------+---------------+---------------------+
|  2 | Marta    | marta@xxx.xxx | 2005-11-06 20:39:08 |
+----+----------+---------------+---------------------+
|  3 | Pedro    | joao@xxx.xxx  | 2005-11-06 20:39:08 |
+----+----------+---------------+---------------------+

You don’t have to define any table structure, just extend de ActiveRecord class and call the parent __construct() method with the table name :

<?php

include_once ‘class.ActiveRecord.php’;

class Person extends ActiveRecord {
    public function __construct() {
        parent::__construct(‘person’);
    }
}

?>

To return all rows in the table:

<?php

$persons = new Person();

/**
 * This will print all records
 * $persons->findAll() will return a Recordset
 */
foreach($persons->findAll() as $person) {
    echo ‘id: ‘.$person->id;
    echo ‘name: ‘.$person->name;
    echo ‘email: ‘.$person->email;
    echo ‘last update: ‘.$person->last_update;
}

/**
 * Alternatively you can ‘walk’ the Recordset
 * with next(), prev(), etc. because Recordset
 * implements the Iterator interface
 */

?>

Insert a record:

<?php

$person = new Person();
$person->name = ‘Julia’;
$person->email = ‘julia@xxx.xxx’;
$person->insert();

?>

Update a record:

<?php

$personId = $_POST[‘id’];
$person = new Person();
$person->id = $personId;
$person->name = ‘Nuno Mariz’;
$person->update();

?>

UPDATE:
With the Pádraic Brady tip for merging the insert() and update() methods to only one save() method, now is possible to:

<?php

// insert
$person = new Person();
$person->name = ‘Nuno Mariz’;
$person->save();

// or update
$personId = $_POST[‘id’];
$person = new Person();
$person->find($personId);
$person->name = ‘Nuno Mariz’;
$person->save();

?>

You can view the UML for the implementation.
See you in part II…

Ruby on Rails first try

Ruby on Rails

For those who are trying to install Ruby on Rails on Debian(in my case 3.1 STABLE), you will notice that your application will show a blank page and the following error on the WEBrick web server in dev/development.log:

 
MissingSourceFile (no such file to load -- irb):
(...)

You must install the following packages:

apt-get install ruby1.8-dev
apt-get install irb
apt-get install libncurses5-dev libreadline5-dev

Strong growth for Debian

Debian -- The Universal Operating System

According to Netcraft, the non-commercial distributions are growing faster than the commercial Linux distributions. In my opinion this is not a big surprise, but with the major companies aquiring some linux distributions like Novell with SUSE, the companies which have partnerships with Novell or Redhat will maintain or migrate for these commercial linux distributions.

Debian is currently the fastest growing Linux distribution for web servers, with more than 1.2 million active sites in December. Debian 3.1 was declared stable in July and it appears that both the anticipation of this release becoming stable, and the release itself, have generated new interest in Debian, after some years where it had lagged behind its more active rivals. This growth is particularly noticeable at some of the larger central European hosting locations, including Komplex, Lycos Europe, Proxad and Deutsche Telecom.

Zend Framework Webcast

Zend Technologies

php|architect has posted the recorded version of their Zend Framework webcast on their site.
I must say is quite impressive. I’ve been developing a new framework to take advantage of the new features of PHP5.
Right now is quite mature and is in prodution, but lacks of some features.
One of the features that is missing is the ActiveRecord that Zend will implement in their new framework.
Quite curious is the ZMail, have almost the same API of my Mailer class.
One of the aspects that im also curious is the ZForms, right now in my framework is quite flexible. I can extend my FormManager class and add the elements that i need, like this:

<?php

include_once ‘class.FormManager.php’;

class FormLogin extends FormManager {
  public function __construct() {
    /*
     * Calling the parent
     * Usage::
     * parent::__construct($name,
     *                     $action = null,
     *                     $method = null,
     *                     $enctype = null,
     *                     $extra = null);
     */
    parent::__construct(‘FormLogin’, null, ‘POST’, null, null);
  }

  // Must implement this method
  public function initElements() {
    /*
     * Adding an Hidden Element
     * Usage:
     * $this->addHiddenElement($name, $value);
     */
    $this->addHiddenElement(‘module’, ‘Authentication’);
    $this->addHiddenElement(‘action’, ‘login’);

     /*
     * Adding an Element
     * Usage:
     * $this->addElement($type, $name, $label, $options);
     */
    $usernameOptions = array(…)
    $this->addElement(‘text’,
                      ‘username’,
                      ‘Username’,
                      $usernameOptions);

     /*
     * Adding a Validator
     * Usage:
     * $this->addValidator($elementName, $validatorObject);
     */
    $this->addValidator(‘username’,
                        new RequiredValidator());
    $this->addValidator(‘username’,
                        new MaxLengthValidator(array(‘length’=>15)));

    $passwordOptions = array(…)
    $this->addElement(‘password’,
                      ‘password’,
                      ‘Password’,
                      $usernameOptions);

    $loginOptions = array(…);
    $this->addElement(’submit’, ‘login’, ‘Login’, $loginOptions);
  }
}

$form = new FormLogin();
$form->render(); // render HTML form
echo $form->getFormStart();
// show the Username label
echo $form->getElementLabel(‘username’);
// show the Username imput
echo $form->getElementInput(‘username’);
// show the Password label
echo $form->getElementLabel(‘password’);
// show the Password input
echo $form->getElementInput(‘password’);
// show the Login submit button
echo $form->getElementInput(‘login’); // show the Login submit button
echo $form->getFormEnd();

?>

Another way is to load the XML configuration for the form:

<?php

include_once ‘class.XMLFormManager.php’;

$form = new XMLFormManager(‘FormLogin.xml’);
$form->render(); // render HTML form
echo $form->getFormStart();
echo $form->getElementLabel(‘username’); // show the Username label
echo $form->getElementInput(‘username’); // show the Username imput
echo $form->getElementLabel(‘password’); // show the Password label
echo $form->getElementInput(‘password’); // show the Password input
echo $form->getElementInput(‘login’); // show the Login submit button
echo $form->getFormEnd();

?>

In the XML way is quicker, i have a web application to generate the XML automatically. I can create or load XML forms and edit with an interface. I can bind elements with database table fields, add and configure validators, etc.

Recently i’ve improved the package to support the binding of an element with a database table field, the syntax is similary but with 2 more parameters in the addElement() method.

Sun Announces Support for PostgreSQL

Sun Microsystems

The server and software company said Thursday that it will integrate PostgreSQL into its Solaris operating system, and will begin offering support services to business customers running the software.

At a press conference here, company executives said Sun engineers will participate in the PostgreSQL open-source project to tune the database for Solaris and beef up its high-end capabilities.

By cnet.com

PHP Collaboration Project

Zend Technologies

WOW. Im already anxious to see this working.
One thing that think that is missing in PHP, is the existence of an web application framework or an Application Server, which standardizes the way PHP applications are built.

What is the PHP Collaboration Project?
The PHP Collaboration Project is an open source initiative through which the PHP community and partners will create an industrial-grade PHP Web application development and deployment environment…

Zend PHP Framework
A Web application framework which standardizes the way PHP applications are built. The Zend PHP Framework accelerates and improves the development and deployment of mission-critical PHP Web applications.

By Joel’s Corner

« Previous PageNext Page »