Django

Solve Django Grappelli Delete or Action dropdown menu doesn’t works

30 May , 2013  

Apparently, Django-grappelli action menu drop-down doesn’t works with default Django 1.4. I tried select item and go to drop-down menu to delete that, but nothing happened.

This is errors from Firebug:

1
2
 $("tr input.action-select").actions();
TypeError: $(...).actions is not a function

And the problem apparently located in STATIC_FILEFINDER which FILESYSTEM finder above AppDirectoriesFinder.

This is the solution:

1
2
3
4
5
6
7
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

Windows Phone

Nokia Lumia 920 or Windows Phone black screen and dead

16 May , 2013  

If your windows phone or Nokia Lumia suddenly blank screen or DEAD, don’t throw away! press Volume Down + Power for 10 seconds. It will revived!

Trust me, Nokia phone isn’t easy to die :)

Django

Run standalone python scripts in Django 1.5

15 May , 2013  

Since setup_environ is deprecated in Django 1.5, we can use os.environ to load environment and run standalone python script.

At this example:

1
2
3
4
5
6
7
myproject
    |
    |
    ---- myapp
           |
           |
            -------- standalone_scripts_is_here.py

And here is the code

1
2
3
4
5
6
7
8
9
10
11
import os
import sys

# Loading Django Environment for standalone Python scripts
CURRENT = os.path.dirname(__file__)
sys.path.insert(0, os.path.realpath(os.path.join(CURRENT, '..')))
sys.path.insert(1, os.path.realpath(os.path.join(CURRENT, '..', 'myproject')))

os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"

....

Windows Phone

Lock 3G 4G network in Nokia Lumia Windows Phone

15 May , 2013  

I use Nokia Lumia 920 at this example. To lock Nokia lumia network on 3G / 4G only, we can do quick setup by:

1. Go to dial-pad
Type : ##3282 and call

For older version, please type : ##3282#.

Click settings on right-bottom
From this settings, we can set network running on 2G only, 3G only or even 4G only (LTE).

Here is the steps:
More…

,

Python

Browsing with minibrowser and proxy settings using PyQt4

14 May , 2013  

When it comes need to have browser that we will using with specific task and run behind proxy, we can rely on PyQT4.

Here is the the code that taken from :
http://code.activestate.com/recipes/576921-using-proxy-connection-for-qwebview/

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
## {{{ http://code.activestate.com/recipes/576921/ (r4)
import os
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *

__version__ = "0.1 20091002"
__appname__ = "minibrowser"

TITLE = "%s %s" % (__appname__, __version__)
HOMEPAGE = "http://example.com/"
HISTORY = os.path.join(os.path.dirname(sys.argv[0]), "%s.log" % (__appname__))

class BrowserWidget(QWidget):
    def __init__(self, datpath, parent=None):
        super(self.__class__, self).__init__(parent)
        self.browser = QWebView()
        self.lineedit = QLineEdit()
       
        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.setMargin(0)
        layout.addWidget(self.lineedit)
        layout.addWidget(self.browser)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.connect(self.lineedit, SIGNAL("returnPressed()"), self.entrytext)

        self.browser.load(QUrl(HOMEPAGE))
        self.browser.show()
       
    def entrytext(self):
        self.browser.load(QUrl(self.lineedit.text()))

class Window(QMainWindow):
    def __init__(self, histlogpath, parent=None):
        super(self.__class__, self).__init__(parent)
        self.browserWindow = BrowserWidget(histlogpath)
        self.setCentralWidget(self.browserWindow)
        self.setWindowTitle(TITLE)

        status = self.statusBar()
        status.setSizeGripEnabled(True)

        self.label = QLabel("")
        status.addWidget(self.label, 1)

        self.connect(self.browserWindow.browser, SIGNAL("loadFinished(bool)"), self.loadFinished)
        self.connect(self.browserWindow.browser, SIGNAL("loadProgress(int)"), self.loading)
        self.histlogpath = histlogpath

    def loadFinished(self, flag):
        """SLOT of load finished.
        """
        self.label.setText("Done")
        open(self.histlogpath, 'a').write(self.browserWindow.browser.url().toString() + "n")

    def loading(self, percent):
        """SLOT of loading progress.
        """
        self.label.setText("Loading %d%%" % percent)
        self.browserWindow.lineedit.setText(self.browserWindow.browser.url().toString())

if __name__ == '__main__':
    QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, "proxy.example.com", 8080))
    app = QApplication(sys.argv)
    window = Window(HISTORY)
    window.show()
    app.exec_()
## end of http://code.activestate.com/recipes/576921/ }}}

,

Python

Install Spynner on Virtualenv

11 May , 2013  

Installing Spynner which using Qt4 and autopy module as it 3rd party is can’t run smooth under virtualenvironment. Thigs to do here :

1. Install Qt4 and make it works with Virtualenv
Follow this links Install pyqt4 on virtualenvironment

2. Install autopy under Virtualenv
We may facing several errors while installing autopy under Virtualenv.

Xtest.h problems :

1
src/keypress.c:10:35: fatal error: X11/extensions/XTest.h: No such file or directory

Solution:

1
sudo yum install libXtst-devel

Png.h problems :

1
src/png_io.c:3:17: fatal error: png.h: No such file or directory

Solution:

1
sudo yum install libpng-devel

3. Install spynner

1
pip install spynner

Python

Add PyQt4 on virtualenv Python

11 May , 2013  

If we want to make PyQt4 accessible from virtualenv, we can put this scripts into “~/.virtualenvs/postmkvirtualenv”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
# This hook is run after a new virtualenv is activated.
LIBS=( PyQt4 sip.so )

PYTHON_VERSION=python$(python -c "import sys; print (str(sys.version_info[0])+'.'+str(sys.version_info[1]))")
VAR=( $(which -a $PYTHON_VERSION) )

GET_PYTHON_LIB_CMD="from distutils.sysconfig import get_python_lib; print (get_python_lib())"
LIB_VIRTUALENV_PATH=$(python -c "$GET_PYTHON_LIB_CMD")
LIB_SYSTEM_PATH=$(${VAR[-1]} -c "$GET_PYTHON_LIB_CMD")

for LIB in ${LIBS[@]}
do
    ln -s $LIB_SYSTEM_PATH/$LIB $LIB_VIRTUALENV_PATH/$LIB
done

2. Copy sip.so into your virtualenv site-packages

1
cp /usr/lib64/python2.7/site-packages/sip.so ~/.virtualenvs/hn/lib64/python2.7/site-packages/

3. Last thing if still doesnt works
Copy the PyQt4 folder :

1
cp -dR /usr/lib64/python2.7/site-packages/PyQt4 ~/.virtualenvs/django/lib/python2.7/site-packages/

On Ubuntu:

1
2
3
sudo apt-get install python-qt4
cp /usr/lib/python2.7/dist-packages/PyQt4 ~/.virtualenvs/django/lib/python2.7/site-packages/
cp /usr/lib/python2.7/dist-packages/PyQt4 ~/.virtualenvs/django/lib/python2.7/site-packages/

OS

Install Python 2.7 Debian 6.0. Squeeze

10 May , 2013  

Here are guide to install Python 2.7 into Debian 6.0 Squeeze

1. Add new repo into “/etc/apt/sources.list”

1
deb http://ftp.uk.debian.org/debian/ testing main contrib non-free

2. Update and Upgrade

1
apt-get update && apt-get upgrade -y

3. Install python 2.7 and set as default

1
2
3
apt-get install libc6-dev
apt-get install python2.7
update-alternatives --install /usr/bin/python python /usr/bin/python2.7 10

Django

Django log format app name and function and saved into file

10 May , 2013  

This is quick configuration for Django logger to log with application name followed with function, and store them into log files.

1. Edit logger settings
settings.py

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
import os
CURRENT = os.path.dirname( __file__ )

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'semi_verbose': {
            'format': '[%(levelname)s] %(module)s %(name)s %(funcName)s(): %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': os.path.abspath(os.path.join(CURRENT, "..", "logs",
                                                     "server")),
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'semi_verbose',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', 'console'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'myapp': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    }
}

More…

,

Django

Get object in Django Admin Form

6 May , 2013  

Easy way to access object in Django admin form template is using {{ original }}

Django

Create custom view and page on Django admin

6 May , 2013  

We can customize Django Admin with custom views and pages. Here are the steps to do:

1. Configure Admin URL
Edit urls.py and append new admin views before “admin.site.urls” :

1
2
3
    ...
    url(r'^admin/item/$', 'products.views.admin_products'),
    url(r'^admin/', include(admin.site.urls)),

2. Create Django admin custom views
Create new admin function view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@login_required
def admin_products(request):
    items_list = Item.objects.all()
    paginator = Paginator(items_list, 25)
    page = request.GET.get('page')

    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        items = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        items = paginator.page(paginator.num_pages)

    data = {"items": items}

    return render(request, "products/admin_item.html", data)

3. Create custom django admin templates
We can use default django admin and modify them later for references instead of building new pages from scratch. We can copy it from “django/contrib/admin/templates/admin” and copy it into templates folder.

Files that usually we need to modified :

1
2
3
4
app_index.html
change_form.html
change_list.html
delete_confirmation.html

OS

Setup git server with Amazon EC2

6 May , 2013  

We can setup git server on amazon ec2 intances using gitolite. Here is step to do:

1. Configure SSH config
Create new file “~/.ssh/config” which contains your amazon EC2 hostname, user and PEM key location.

1
2
3
4
Host amazon
Hostname 23.21.1xx.xxx
User root
IdentityFile /home/yodi/my-ec2-micro.pem

With this configuration, we can login into EC2 instance with : “ssh amazon”

2. Copy our SSH public keys into Amazon EC2

1
2
3
ssh-keygen -t rsa
cp ~/.ssh/id_rsa.pub /tmp/local.pub
rsync -avr /tmp/local.pub -e "ssh -i /home/yodi/my-ec2-micro.pem" root@23.21.1xx.xxx:/tmp/local.pub

3. Login into EC2 and setup gitolite
Install gitolite :

1
sudo apt-get install git gitolite git-daemon-run

Create new git account for gitolite:

1
2
3
4
5
sudo adduser --system --shell /bin/bash --gecos 'git version control' --group --disabled-password --home /home/git git
su git
cd /home/git
echo "PATH=$HOME/bin:$PATH" > .bashrc
gl-setup /tmp/local.pub

Back to your local machine and clone admin gitolite repo:

1
git clone git@amazon:gitolite-admin.git

Voila! now we can start add new repository! :)

Create new repository by editing “gitolite-admin/conf/gitolite.conf”, eg :

1
2
3
4
5
repo gitolite-admin
RW+ = @all

repo insurances
RW+ = @all

Then you can try to commit this repo :

1
2
git commit -am 'create new repo'
git push origin master

Then you can clone new repo by :

1
git clone git@:insurances

,

Django

Make auto populated slug field in Django admin

5 May , 2013  

Django admin have great feature called “prepopulated”. Here is an example to create auto populated slug in Django admin without using any additional Jquery scripts.

1
2
3
4
5
6
7
8
9
10
11
from django.contrib import admin
from photos.forms import PhotoAdminForm
from photos.models import Photo

class PhotoAdmin(admin.ModelAdmin):
    list_display = ('title', 'admin_image')
    prepopulated_fields = {'slug':('title',)}

    form = PhotoAdminForm

admin.site.register(Photo, PhotoAdmin)