Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Saturday, January 22, 2011

Where Django & PyDev fails

Don't get me wrong, I like Python, PyDev and Django. But I simply hate the small problems like this:


I forget something simple, like what was the order of return tuple of get_or_create? Then I try to look the tip of the function, and what do I get? The useless **kwargs passing.

Same thing with the god damned exception handling. I don't think I've seen any official package that lists the exceptions given function may rise. All functions should have a good doc-strings that lists parameters, exceptions (including nested) and in case the return value is tuple or something non obvious the order of items in tuple.

Simply, it takes ages to open up the webpage, and browse to right place of docs. There exists a fix, but PyDev does not support it. It's the official objects.inv for Django (sphinx mapping file from keyword to URI).

Thursday, February 12, 2009

Django and Eclipse

(When I have interest, I have planned to convert this to HTML, for now, let it be Plain text)
Anyone is welcome to edit, repost and/or distribute the following instructions, I just have a little wish: Provide link for this post.

Used: Eclipse Classic Ganymede (3.4.1), Django 1.0.2, PyDev

Install Pydev
=============
... TODO ...

Python interpreters (Eclipse preferences -> Pydev -> Interpreter - Python)
--------------------------------------------------------------------------
Press `New`
Type (Ubuntu) `/usr/bin/python`
Type (Windows) `C:\Python25\python.exe` *** Warning: not tested!
Press `Ok`
*IMPORTANT!*
If you have installed Django to site-packages
*UNCHECK* I repeat *UN*CHECK the Django from the Pythonpath list
(Or remove from the list)
(We are *NOT* going to use the site-packages django to this for development purposes)

Django project for Eclipse
==========================

File -> New -> Pydev project
Project name: `Django`
Grammar version: `2.5`
Uncheck `Create default `src` folder and add it to the pythonpath?`
Error about interpreter?: `Click here to configure an interpreter not listed` see above Install Pydev section


Pydev Package Explorer (the "file tree" on the left) -> Django (right click) -> Properties
PyDev - PYTHONPATH
Add source folder -> Choose `Django` (the project's "root" directory, for why, see (*1))

(Ubuntu) in terminal (go to your eclipse workspace directory):
cd Django/
svn co http://code.djangoproject.com/svn/django/tags/releases/1.0.2/ .

(Windows) Extract the django release to the Django/ dir:
(after extraction you should have directories like `Django/django`, `Django/examples`, `Django/docs` ...)

Pydev Package Explorer (the "file tree" on the left) -> Django (right click) -> Refresh (now zip some coffee, this might take while)

All is set for Django project.

(*1) Why root? Because for instance `django` and `examples` directories in django distribution should be in pythonpath and they are in root, this is only reasonable way since we won't relocate them.


My django project:
==================

VERY IMPORTANT! DO THE DAMN `Django project for Eclipse` section FIRST! SINCE YOU WON'T GET THE AUTOCOMPLETE/*PLUGGABLE DJANGO VERSION BETWEEN APPLICATIONS* WITHOUT IT.

File -> New -> Pydev project
Project name: `Django Poll`
Grammar version: `2.5`
*Check* I repeat *Check* (It should be checked by default) the `Create default `src` folder and add it to the pythonpath?`
Error about interpreter?: This can't be, you set it up on `Django project for Eclipse`
Click `Next`
(In reference page)
Check `Django` (the Django project you created earlier, remember that?)
Press `Finish`

Django-admin.py from within Eclipse:
------------------------------------

Run -> External tools -> External tools configurations
Left side tree: Right click `Program` -> New
Name: `Django-admin (for project src directory)`
Location (Ubuntu): `/bin/bash`
Location (Windows): `c:\Windows\system32\cmd.exe` *** Warning: Not tested
Working directory: `${project_loc}/src`

Environment tab:
New (from right)
Name: `PATH`
Value (Ubuntu): `${env_var:PATH}:${workspace_loc:Django/django/bin}`
Value (Windows): `${env_var:PATH};${workspace_loc:Django/django/bin}` *** Warning: Not tested
Click `Ok`
New (from right)
Name: `PYTHONPATH`
Value (Ubuntu): `${project_loc}/src:${workspace_loc:Django/}`
Value (Windows): `${project_loc}/src;${workspace_loc:Django/}` *** Warning: Not tested
Click `Ok`

Press `Apply` and `Close` (Don't try to Run, it will (most likely) give error)

Run -> External tools -> Organize favorites
Click `Add`
Choose `Django-admin (for project src directory)`
Click `Ok`
Click `Ok`

Now in order to run this tool one must do *TWO* things:

1.) Pydev Package Explorer (the "file tree" on the left) -> Click on the `Django Poll` project (even if it is selected, just click it (to get focus on it))

2.) Run -> External tools -> `Django-admin (for project src directory)`
*** If you get error about `Variable references empty selection: ${project_loc}`, you didn't do 1.) well enough, you *MUST* click it first and nothing else afterwards, the *project folder* in *Pydev Package Explorer* must have *focus* (being selected is not enough)!

Console window (if not visible do Window -> Show view -> Console), type:
`django-admin.py`

If all went well you should get something like: `Type django-admin.py help for usage.`

Following is from official django tutorial http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01

Console window, type:
`django-admin.py startproject mysite`

PyDev Package Explorer (the tree on the left) -> `Django Poll` (right click) -> Refresh
(If all worked well you should now have directory `src/mysite` in your project)

Manage.py from within Eclipse
-----------------------------

PyDev package explorer (tree in the left) -> `Django Poll` (your project name) -> src -> manage.py (right click) -> Properties
(You should be in dialog called `Properties for manage.py`)
Click `New...`
Choose `Python Run`
(For reason unknown Eclipse doesn't prepopulate the following fields)
Name: `Django Poll -- Custom manage.py` (Yes you read it right, I prefixed it with project name for extra verbosity)

Main tab (default tab):
Project click `Browse`, choose your project `Django Poll`
Main module click `Browse`, choose `src -> mysite -> manage.py`, click `Ok` (it should now read ${workspace_loc:Django Poll/src/mysite/manage.py} )

Arguments tab:
Press `Variables` (from Program arguments)
Choose `string_prompt`
(It should have added this `${string_prompt}`)
Click `Ok`
Click `Ok`
Click `Ok`


Running test:

Locate Run button from toolbar (Green play button, with arrow downwards next to it), press the arrow -> Choose `Organize Favorites`
Press `Add...`
Check the `Django Poll: Custom manage.py`

Run button (press the arrow) -> `Django Poll -- Custom manage.py`
(If all went well, you should be given prompt)
Type: `help`
(If all worked well, you should get long list of commands, beginning:

`Type 'manage.py help <subcommand>' for help on a specific subcommand.`
...)


Lets create app:

Run button press the arrow -> `Django Poll -- Custom manage.py`
Type: `startapp polls`

Now refresh your project directory from Pydev Package explorer (the tree in the left)
(If all worked well you should now have directory `src/mysite/polls` in your project)


Running the development server
------------------------------
Run button (press the arrow) -> `Django Poll -- Custom manage.py`
Type: `runserver --noreload`

(You can use it without `--noreload`, but the console window is rather useless in that case, since Eclipse can't handle the refresh behaviour of `manage.py`.)


Other Eclipse preferences (optional), though highly recommended
===============================================================

More run configurations
-----------------------
Since you most likely need manage.py's commands `runserver`, `syncdb`, `reset` the most, create own run configurations for those, using similar steps as in "Manage.py from within Eclipse" section.


Tasks of project
----------------

Window -> Show view -> Tasks

Tasks (little `downward triangle` before minimize of tasks window) -> Configure contents
Right side of the window: check `On any element in same project`
Left side of the window: check `TODOs`


Monday, August 18, 2008

Django 1.0 custom admin two fields shown as one

I needed a way to have two model fields to be shown/edited on one form field. And I came up with the following.

(CurrencyField (expense) shows and edits fields `value` and `currency` in the actual model)

from django.contrib import admin
from budget.models import Expense
from django import forms
from django.forms.util import ValidationError

class CurrencyField(forms.CharField):
def clean(self, value):
amount = 0
currency = ''
try:
amount = float(value.split(" ")[0].strip())
except (ValueError, TypeError), te:
raise ValidationError('Amount is incorrect!')

try:
currency = value.split(" ")[1].strip().upper()
if len(currency) != 3:
raise TypeError('cur')
except (ValueError, TypeError), te:
raise ValidationError('Currency is incorrect! Should be three letter universal sign (e.g. EUR)')

return (amount, currency)

class ExpenseForm(forms.ModelForm):
expense = CurrencyField()
def __init__(self, *args, **kwargs):
super(ExpenseForm, self).__init__(*args, **kwargs)
self.initial['expense'] = "%s %s" % (self.instance.value or '',
self.instance.currency or '')

def save(self, commit=True):
self.instance.value, self.instance.currency = self.cleaned_data['expense']
return super(ExpenseForm, self).save(commit)

class Meta:
model = Expense

# Note added:
# Expense is like this:
# class Expense(models.Model):
# ...
# value = models.FloatField(...) # This contains the amount of currency, like 120.32
# currency = models.CharField(...) # Currency is e.g. 'USD', 'EUR' identifier of currency
# ...

class ExpenseAdmin(admin.ModelAdmin):
list_display = ('date', 'time', 'local_currency', 'in_euro', 'description', 'tags')
ordering = ('date','time')
form = ExpenseForm
fields = ('expense', 'date', 'time', 'description', 'tags')

admin.site.register(Expense, ExpenseAdmin)

Tuesday, August 12, 2008

Django 1.0 admin custom inlines


...

class ChangeSetForm(forms.ModelForm):
dosomething = forms.BooleanField(label="Do something")
class Meta:
model = ChangeSet
exclude = ('modified',) # Note: This doesn't work!
fields = ('old_title',) # Note: This doesn't work!

ChangeSetInlineFormSet = inlineformset_factory(
Article, ChangeSet,
form = ChangeSetForm
)

class InlineChangeSet(admin.TabularInline):
model = ChangeSet
form = ChangeSetForm
extra = 0
raw_id_fields = ('editor',)
fields = ('old_title', ) # This works.

...

Completely custom inline (without delete checkbox etc)


coming...

Tuesday, July 15, 2008

Installation of MySQL server, MySQLdb, Flup, Lighttpd and Django (Debian etch)

Note: I have not tested it as is, I was writing this afterwards from memory, so beware of the errors.

Setting up debian


# logged in as root:
apt-get install sudo
adduser joe
sudoedit /etc/sudoers
joe ALL=(ALL) ALL # added this line

# Following is done in my own user (joe):
sudo apt-get upgrade
sudo dpkg-reconfigure locales
sudo tzselect
sudo apt-get install build-essential


Now to the installing Django and others...


# Python 2.5
sudo apt-get install python2.5
sudo rm /usr/bin/python
sudo ln -s /usr/bin/python /usr/bin/python2.5

python
Python 2.5 (release25-maint, Dec 9 2006, 14:35:53)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

# Storing downloaded/compiled python-modules:
sudo mkdir /usr/src/python-modules


# MySQL server:
sudo apt-get install mysql-server

# MySQLdb:
# Dependencies:
sudo apt-get install libmysqlclient15-dev
sudo apt-get install python2.5-dev

cd /usr/src/python-modules/
sudo wget http://mesh.dl.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.2.tar.gz
sudo tar -xvzf MySQL-python-1.2.2.tar.gz
cd MySQL-python-1.2.2
python setup.py build
sudo python setup.py install
cd /usr/src/python-modules/

python
>>> import MySQLdb
>>>


# Flup (for the fastcgi):
cd /usr/src/python-modules/
svn co http://svn.saddi.com/flup/trunk/ flup-svn
cd flup-svn
sudo python setup.py install
cd /usr/src/python-modules/

python
>>> import flup
>>>


# Lighttpd (1.4.19) installation using Debian unstable repository:
# TODO: Coming...

# NOTE: My installation method of Django allows to use both, svn and release
# Django as far as you always run the wanted django using env PYTHONPATH...
# Django release installation:
cd /usr/src/python-modules/
sudo wget http://www.djangoproject.com/download/0.96.2/tarball/ # this one downloads Django-0.96.2.tar.gz
sudo tar -xvzf Django-0.96.2.tar.gz

env PYTHONPATH=$PYTHONPATH:/usr/src/python-modules/Django-0.96.2 python
>>> import django
>>>

# Django svn installation:
cd /usr/src/python-modules/
sudo svn co http://code.djangoproject.com/svn/django/trunk/ Django-svn

env PYTHONPATH=$PYTHONPATH:/usr/src/python-modules/Django-svn python
>>> import django
>>>

# Django new project and fastcgi server:
sudo mkdir /var/www-domains/

sudo adduser examplecom
sudo mkdir /var/www-domains/example.com/
sudo chown examplecom:examplecom /var/www/example.com
sudo chmod +s /var/www/example.com

sudo su examplecom
cd /var/www/example.com/
mkdir public
mkdir public_media
mkdir fastcgi-servers
mkdir django-projects

# TODO: More to come...