How to sort instance by key or values inside list in Python

Sometimes we need to sorting a list which contain instances. And we need to sort by instances keys or values.
This commonly happen in Django. So, basically, we just assign instance into dictionary and create index by key/values taken instance property.
Then, we can sort and save into list.

For instance :

1
2
3
4
5
data_list = ['223232', '23232211', '333333']
collection = []
for data in data_list:
     place = Place.objects.get(id=data)
     collection.append(place)

We want to sort collection which it list that contain Instance from Django Models.
So, we can modify this code by :

1
2
3
4
5
6
7
8
9
10
11
12
data_list = ['223232', '23232211', '333333']
collection = []
temporary = {}

for data in data_list:
    place = Place.objects.get(id=data)
    temporary[place.name] = place

temporary = sorted(temporary.items())

for place_val in temporary:
    collection.append(place_val[1])

Simple!

Posted in Django | Tagged | Leave a comment

Solve EnvironmentError: mysql_config not found Mysql-Python pip on Ubuntu

If you installing MySQL-python from pip in Ubuntu and see this error :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Downloading/unpacking MySQL-python==1.2.3 (from -r requirements.txt (line 3))
  Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
  Running setup.py egg_info for package MySQL-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/ubuntu/.virtualenvs/trip/build/MySQL-python/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/ubuntu/.virtualenvs/trip/build/MySQL-python/setup.py", line 15, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /home/ubuntu/.virtualenvs/trip/build/MySQL-python
Storing complete log in /home/ubuntu/.pip/pip.log
(trip) ubuntu@ubuntu:~/Tripvillas/tripvillas[yodi]$ pip install -r requirements.txt
Downloading/unpacking git+https://github.com/yuchant/django-mailer.git (from -r requirements.txt (line 11))
  Cloning https://github.com/yuchant/django-mailer.git to /tmp/pip-PUZNs4-build
  Running setup.py egg_info for package from git+https://github.com/yuchant/django-mailer.git
   
Downloading/unpacking http://labix.org/download/python-dateutil/python-dateutil-1.5.tar.gz (from -r requirements.txt (line 26))
  Downloading python-dateutil-1.5.tar.gz (232Kb): 232Kb downloaded
  Running setup.py egg_info for package from http://labix.org/download/python-dateutil/python-dateutil-1.5.tar.gz
   
Downloading/unpacking Django==1.3.1 (from -r requirements.txt (line 2))
  Running setup.py egg_info for package Django
   
Downloading/unpacking MySQL-python==1.2.3 (from -r requirements.txt (line 3))
  Running setup.py egg_info for package MySQL-python
    sh: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 24, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    Complete output from command python setup.py egg_info:
    sh: mysql_config: not found

Traceback (most recent call last):

  File "<string>", line 14, in <module>
    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 24, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found

----------------------------------------

This mean you should install libmysqlclient-dev. On Ubuntu 11.10 Oneiric :

1
sudo apt-get install libmysqlclient-dev libmysqlclient-dev libmysqlclient16
Posted in Python module | Tagged | Leave a comment

Setup Logger in Django 1.3 to show warning & error in console development

New guys in Django commonly have a headache to see Logger configuration in settings.py. Sometimes people only want use Logger to print error / warning / debug in server development. Here are how to do that.

First, open up your settings.py and see at logger section :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Continue reading

Posted in Django | Tagged , | Leave a comment

Example how to rsync and restart services remote server using Fabric

Fabric is great tools in Python which can ease our development. You can start installing it by :

1
sudo pip install fabric

Let create some example cases here.
1. I have remote server which have port SSH (it a must!) and use SSH-key (PEM) for login.
2. I have django apps that located in PROJECT_PATH (eg: ~/htdocs/pricedag)

So, we need create fabfile.py in PROJECT_PATH :
Continue reading

Posted in Django | Tagged , | Leave a comment

create simple example JSON REST API in Django 1.3

Creating REST JSON API in Django in pretty easy. I know several django modules like django-tastypie, django piston, etc provide easy ways to build REST API in Django, but at this time, I will show simple example.

First, we should define our urls. Eg : “/api/search/keyword”

APP/urls.py

1
2
3
4
5
6
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('price.views',
    url(r'^api/search/(?P<keyword>[a-zA-Z0-9\s\+]+)$', 'search', name='search'),
)
</keyword>

Continue reading

Posted in Django | Tagged , | 2 Comments

Python Requests Module get Json content into dictionaries

Requests Module is great python module to use urllib2 in easy ways. For instance, let we get some JSON from my Gravatar :

1
https://es.gravatar.com/bashlook.json

In case you need how to get JSON value using urllib2 :

1
2
3
4
5
6
7
8
9
10
11
import urllib2
import json

uri = "https://es.gravatar.com/bashlook.json"
opener = urllib2.urlopen(uri)

try:
    result = json.load(opener)
except ValueError, e:
    errorMessage = str(result) + ':' + str(e)
    return errorMessage

At this cases, “result” can be accessed as dictionaries, example :

1
result['entry']

Continue reading

Posted in Python module | Tagged , | Leave a comment

Delete FileField using delete(save=False) in signals post_delete Django

We can’t overwrite delete() for deleting FileField and related files in Django. As we know that :

In Django 1.3, when a model is deleted the FileField’s delete() method won’t be called. If you need cleanup of orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).

Continue reading

Posted in Django | Tagged , | Leave a comment

ValueError: invalid literal for int() with base 10 when do Django Filter()

Do you got this error while doing filter QuerySet in Django:

1
ValueError: invalid literal for int() with base 10:

It just simply mistake that may you usually do by filter() with args or kwargs.
This is some bad code :
Continue reading

Posted in Django | Tagged , | Leave a comment

Filter DateTimeField Models with Date format in Django

When we have DateTimeField, sometimes we have a need to filter it by Date. For example, given a models called “Insurance” :

1
2
3
class Insurance(models.Model):
    name = models.CharField(max_length=255)
    created = models.DateTimeField()

Given data :

1
2
3
4
5
6
7
8
===================================
| Name     |  Created             |
===================================
| Yodi     | 2012-01-03 03:01:01  |
| Toms     | 2012-01-03 03:34:21  |          
| Mandy    | 2012-01-04 04:08:41  |          
| Tara     | 2012-01-05 05:24:11  |          
........

Continue reading

Posted in Django | Tagged , | 1 Comment

How to convert queryset models into list in Django

This is common question that we need to return Queryset in Django just to be a list. When I try ask to several friends, most of them show me bunch of iterating codes. For example :

1
2
3
4
5
6
7
Insurance
============================
| ID   |  Client    | ...  |
============================
| 1    | Yodiaditya |  ...
| 2    | John       |  ....
| 3    | Yodiaditya |  ....
1
insurer_list = Insurance.object.filter(client="yodiaditya")

Continue reading

Posted in Django | Tagged , | Leave a comment