Debian and Ubuntu server locale and encoding

I recently had «fun» supporting server installation of software that needed locale set properly.

In Debian, you can just use

dpkg-reconfigure locales

and the console GUI will pop up.

In Ubuntu server, you’ll more steps to make^

http://askubuntu.com/questions/89976/how-to-change-the-default-locale-in-ubuntu-10-10-server

https://debian.pro/503

https://help.ubuntu.com/community/Locale

And make full use of UTF, please: http://docs.python.org/2/library/locale.html

Django soft image thumbnail replacement

Using new template tag, you’re now free to cache images before rolling out new design and avoid heavy load (maybe via random call)!

https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#with

<img src="{{img.url|thumb:"500x500"%}" />


{% if rand % 10 }
{with newthumb=img.newthumb %}}

or <!-- {{img.url|thumb:"500x580"%} -->

{% endif %}

MySQL with Django on Debian

First, install MySQL driver for Python:

sudo apt-get install python-mysqldb

Next, modify your config of MySQL: http://dba.stackexchange.com/a/8289

If you’ve already messed up the install, you can either drop/create database from scratch, or apply the following script to every table of your DB:

ALTER TABLE `table` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Alternative mirgation path: http://docs.joomla.org/Convert_a_MySQL_database_to_UTF-8

Django nginx Debian

How to make a simple install of django onto small Debian-6 VPS.
I’ll stick with flup, which enables python to serve fastcgi and some other protocols.
I use it in conjunction with nginx, which in turn is used save memory.

Literature:
http://library.linode.com/using-linux/administration-basics#system_diagnostics
http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/
http://www.mindinmotion.ru/post/django-postgresql-nginx-on-debian-server
Читать далее

Django и Windows

Многое изменилось. Django теперь не хочет обновлений из транка — рекомендует только релизы.
Чтоб установить на винду, потребуется распаковать, запустить сетап, попить чаю. Затем добавить в переменную окружения папку C:Python27Libsite-packagesdjangobin или ту, в которой у вас питон.
Затем нужно доработать напильником, ведь я за PowerShell.
profile.ps1:
function django-admin {python (gcm django-admin.py | resolve-path) $args}
Нужные команды:
django-admin startproject
manage.py runserver

Django и SAPE

Для многих является препятствием, если код биржи или партнерки написан на PHP. Я решил твердо использовать MVC. И не Zend.
Код сапы поддается легко, итак:

По последнему интро:

Использует shelve, а тот, в свою очередь — dbm, что легче полного распарсивания.

Миграции БД в Django, SQLite

UPD2: http://south.aeracode.org/ стал де-факто стандартом миграций в django.

UPD: Найден новый проект миграции БД, возможно, все нижеизложенное актуально только для SQLite
Вот нашел в интернете интересную статью об обновлении БД, но сайт стал приватным, поэтому вот последний образец:

As I found out in my previous post it is not possible to modify your database schema via Django. This means once you have created the schema for your models, the only thing you can do is add more models using:

python manage.py syncdb

If you make a change to a model you are on your own.
When I defined my first model for a node (as in a node in a hierarchy) the model was something like this:

class Node(models.Model):
    title = models.CharField(max_length=100)
    sort_order = models.IntegerField(default=1)
    menu = models.ForeignKey('Menu')
    parent = models.ForeignKey('self')
    is_visible = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

The problem with this is that this model does not allow for a root node, since the parent column is a foreign key on itself, but the root node must by definition not have a parent (that is parent = NULL in the database). So I changed the model to this:

class Node(models.Model):
    title = models.CharField(max_length=100)
    sort_order = models.IntegerField(default=1)
    menu = models.ForeignKey('Menu')
    parent = models.ForeignKey('self', blank=True, null=True)
    is_visible = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

This allows the parent column to be null and is fine for the model, but now I need to make the change to the schema manually in sqlite.
So first I run this script to see what table schema the model is expecting:
python manage.py sql cwcms
Which brings back this:

CREATE TABLE "cwcms_node" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(100) NOT NULL,
    "sort_order" integer NOT NULL,
    "menu_id" integer NOT NULL REFERENCES "cwcms_menu" ("id"),
    "parent_id" integer NULL,
    "is_visible" bool NOT NULL
)
;

I then need to log in to sqlite and make the change to theschema to reflect this. This is easily done with the manage.py script:
python manage.py dbshell
Next, because sqlite only supports basic ALTER TABLE syntax (ie you can’t change column definitions) you essentially need to create your new table schema using a different name. Then copy the contents from the old table into the new one, delete the old table and then rename the new table to the name of the old table (ie the one that Django is expecting). The series of statements would look something like this:

CREATE TABLE "cwcms_node_new" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(100) NOT NULL,
    "sort_order" integer NOT NULL,
    "menu_id" integer NOT NULL REFERENCES "cwcms_menu" ("id"),
    "parent_id" integer NULL,
    "is_visible" bool NOT NULL
);

INSERT INTO cwcms_node_new SELECT * FROM cwcms_node;

DROP TABLE cwcms_node;

ALTER TABLE cwcms_node_new RENAME TO cwcms_node;

Another way of doing this if you’re still early on in development is to simply get the commands needed to clear the database using manage.py:
python manage.py sqlclear cwcms
And run them on the your sqlite database and use syncdb to recreate your whole database.