วันจันทร์ที่ 20 พฤษภาคม พ.ศ. 2556

How to Use South in Django to Manage Database

Overview

South is a module to help managing database tables when you update models in Django.
Steps to start using South described below.

Described here is case with existing project + database just created + no table created yet
see detail for other cases here >> http://stackoverflow.com/questions/4840102/how-come-my-south-migrations-doesnt-work-for-django


Install South


detail here >> http://south.readthedocs.org/en/0.7.6/
  sudo easy_install South


Initiate South in Legacy Project + No Database

1. add South to INSTALLED_APPS in your settings.py file (not add your application at this step)
2. run python manage.py syncdb
    this will create South table south_migrationhistory in your database.
    skip this step, you will encounter error "Table 'app_name.south_migrationhistory' doesn't exist" when you run command python manage.py migrate app_name in step 5
3. now add your application to INSTALLED_APPS in your settings.py file
4. run python manage.py schemamigration app_name --initial
    this will create initial migration record
5. run python manage.py migrate app_name
If any error occur, you can reset South history as described below.

Reset South History 

detail here >> http://stackoverflow.com/questions/4625712/whats-the-recommended-approach-to-resetting-migration-history-using-django-sout
in case of any error, use following commands

  rm -r appname/migrations/ 
  python manage.py reset south << see NOTE below before run this command
  python manage.py convert_to_south appname 
then drop all related database tables, and initiate South again as described above.
NOTE:
- reset south will delete ALL migration history for all apps that you have installed.
  avoid using this if you only want to remove migration history of some specific app. selectively delete from table south_migrationhistory instead.
  e.g. delete from south_migrationhistory where app_name = 'homepage';
- last command, convert_to_south, use to avoid dropping all your tables. it is equivalent to these two commands
  python manage.py schemamigration --initial app_name_1
  python manage.py schemamigration --initial app_name_2
     ...
  python manage.py migrate --fake

Ongoing Maintenance

after modify models, run following commands
  python manage.py schemamigration app_name --auto
  python manage.py migrate app_name




วันเสาร์ที่ 18 พฤษภาคม พ.ศ. 2556

Customize Ubuntu 12.04

How to Change Launcher Icon Size in Unity2d

Set shortcut key

- switch keyboard layout (e.g. TH <--> EN)
  System Settings > Keyboard Layout > Options > Key(s) to change layout
- hide all open windows (i.e. show desktop)
  System Settings > Keyboard > Shortcuts > Navigation > Hide all normal windows
  NOTE: Super key = Windows key; set keyboard layout to EN before changing any shortcut

How to Hide Devices from Ubuntu

How to Add Image to Ubuntu Wallpaper List

Setup Japanese Input

วันเสาร์ที่ 4 พฤษภาคม พ.ศ. 2556

Python Regular Expression Cheat Sheet


Meta-Character

[a-c], [abc] : a, b, c
[^5] : all chars except 5
\d : [0-9] decimal digit
\D : [^0-9] non-digit chars
\s : [ \t\n\r\f\v] whitespace chars
\S : [^ \t\n\r\f\v] non-whitespace chars
\w : [a-zA-Z0-9_] alphanumeric chars
\W : [^a-zA-Z0-9_] non-alphanumeric chars
^ : beginning of line
\A : beginning of string (differ from ^ for multi-line string)
$ : end of line
\Z : end of string (differ from ^ for multi-line string)
\b : word boundary
\B : non-word boundary
() : group e.g. (ab)+ match ab, abab, ababab, ...
\1, \2, ... : reference to group 1, group 2, ...
(?P<name>...) : grouped name, e.g. (?P<word>\b\w+\b) : matched group (\b\w+\b) will be named word

Repeating

* : 0+ repeating (greedy repeating : get as much as it could)
+ : 1+ repeating (greedy repeating : get as much as it could)
? : 0..1 repeating = {0,1} (greedy repeating : get as much as it could)
*?, +?, ?? : same as above but non-greedy repeating
{m} : exactly repeating m times
{m,n} : m..n repeating
{,n} : 0..n repeating
{m,} : m.. repeating

Usage - Pattern object

compile() : compile pattern string to Pattern object
match() : matches at the beginning of the string, return Match object or None if not match
search() : matches at any location of the string, return Match object or None if not match
findall() : return all matched substrings as a list
finditer() : return all matched substrings as an iterator
Usage - Module level
re.match(<regex string>, <target string>) :
re.search(...)
re.findall(...)
re.finditer(...)

Usage - Match object

group() : return matched string
start() : return starting position (0-indexed)
end() : return ending position (0-indexed, excluded)
span() return tuple of (start, end) positions
match length = end() - start()

Sample

>>> import re
>>> p = re.compile(’[a-z]+’)
>>> p.match("")
>>> print p.match("")
None
>>> m = p.match(’tempo’)
>>> m.group()
’tempo’
>>> m.start(), m.end()
(0, 5)
>>> m.span()
(0, 5)
>>>
>>>
>>> m = p.search(’::: message’)
>>> m.group()
’message’
>>> m.span()
(4, 11)
>>>
>>>
>>> p = re.compile(’\d+’)
>>> p.findall(’12 drummers drumming, 11 pipers piping, 10 lords a-leaping’)
[’12’, ’11’, ’10’]
>>> iterator = p.finditer(’12 drummers drumming, 11 ... 10 ...’)
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)
>>>
>>>
>>> p = re.compile(r’(?P<word>\b\w+\b)’)
>>> m = p.search( ’(((( Lots of punctuation )))’ )
>>> m.group(’word’)
’Lots’
>>> m.group(1)
’Lots’
>>>
>>>
>>> p = re.compile(r’\W+’)
>>> p2 = re.compile(r’(\W+)’)
>>> p.split(’This... is a test.’) # delimiter not included
[’This’, ’is’, ’a’, ’test’, ’’]
>>> p2.split(’This... is a test.’) # delimiter included
[’This’, ’... ’, ’is’, ’ ’, ’a’, ’ ’, ’test’, ’.’, ’’]
>>>
>>>
>>> p = re.compile( ’(blue|white|red)’)
>>> p.sub( ’colour’, ’blue socks and red shoes’)
’colour socks and colour shoes’
>>> p.sub( ’colour’, ’blue socks and red shoes’, count=1)
’colour socks and red shoes’
>>>
>>>
>>> s = ’<html><head><title>Title</title>’
>>> len(s)
32
>>> print re.match(’<.*>’, s).span()
(0, 32)
>>> print re.match(’<.*>’, s).group() # greedy match
<html><head><title>Title</title>
>>> print re.match(’<.*?>’, s).group() # non-greedy match, others are *?, +?, ??, or {m,n}?
<html>

วันพุธที่ 1 พฤษภาคม พ.ศ. 2556

Django Model Cheat Sheet

Field Types + Specific Options

<< boolean >>
- BooleanField << True/False
- NullBooleanField << null/True/False

<< number >>
- IntegerField
- SmallIntegerField
- PositiveIntegerField
- PositiveSmallIntegerField
- BigIntegerField << 64-bit integer
- AutoField << auto-incremental IntegerField
- DecimalField
  max_digits, decimal_places << 999.99 : max_digit=5, decimal_places=2
- FloatField

<< text >>
- CharField
  max_length << length in characters
- TextField
- SlugField
- CommaSeparatedIntegerField
- URLField
  verify_exists
- EmailField
  max_length=75
- IPAddressField
- GenericIPAddressField

<< date/time >>
- DateField, DateTimeField, TimeField
  auto_now=False << set current timestamp for every save
  auto_now_add=False << set current timestamp when first create

<< file >>
- FileField << file upload field
  upload_to << path appended to MEDIA_ROOT; can be callable object; can use strftime() formatting
  max_length=100
- ImageField << subclass from FileField
  height_field, width_field << auto-set
- FilePathField

<< relationship >>
- ForeignKey(one-sided model) << many-to-one relationship
  limit_choices_to << effect Admin/ModelForm choices
    e.g. limit_choices_to = {’pub_date__lte’: datetime.now}
  related_name << backward relationship (1 --> many)
  to_field
  on_delete=models.CASCADE << emulate ON DELETE CASCADE behavior
    e.g. user = models.ForeignKey(on_delete=models.SET_NULL) << when delete parent, set reference to NULL
    CASCADE = also delete child when parent is deleted
    PROTECT = cannot delete parent if child exists
    SET_NULL
    SET_DEFAULT = set to default value if parent deleted
    SET()
    DO_NOTHING
- ManyToManyField(other model) << many-to-many relationship
  related_name << same as ForeignKey
  limit_choices_to << same as ForeignKey
  symmetrical << for self-reference
  through << intermidiary model (for additional data)
  db_table << table to store many-to-many relationship
- OneToOneField << one-to-one relationship
  parent_link=False << True=link back to parent class (in subclass model)

(General) Field Options

- null=False << allow null in database
- blank=False << for validation
- default << default value
- choices << value stored + value displayed
    YEAR_IN_SCHOOL_CHOICES = (
        (’FR’, ’Freshman’),
        (’SO’, ’Sophomore’),
        (’JR’, ’Junior’),
        (’SR’, ’Senior’),
        (’GR’, ’Graduate’),
    )
    MEDIA_CHOICES = (
        (’Audio’, (
            (’vinyl’, ’Vinyl’),
            (’cd’, ’CD’),
        )),
        (’Video’, (
            (’vhs’, ’VHS Tape’),
            (’dvd’, ’DVD’),
        )),
        (’unknown’, ’Unknown’),
    )
- db_column << column name in database (override auto-generated column name)
- db_index << True = create index for this field
- editable=True << False = not displayed for edit in form
- unique << True = unique value in field
  unique_for_date, unique_for_month, unique_for_year
- primary_key << True = primary key for model (override auto-generated PK field)
- help_text << display with form widget
- verbose_name << human-readable name

Meta Options

- verbose_name, verbose_name_plural
  human-readable name for model
- unique_together
  combinated unique fields, e.g. unique_together = (("driver", "restaurant"),)
- abstract
  True=model for abstract class
- db_table
  database table used for model
- get_latest_by
  DateField/DateTimeField used to identify latest data (use in manager's latest() method)
- ordering
  default order when get, e.g. ordering = [’-order_date’] << order by order_date descending
- order_with_respect_to
  True=children has order related to its parent (add additional column suffixed _order)
  set at child model;
  parent model can get ordered children using get_<RELATED>_order()
  parent model can set children order using set_<RELATED>_order()
  child model can use get_next_in_order(), get_previous_in_order()
- app_label
  use when model exists outside standard models.py