Django

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

24 Feb , 2012  

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 :
More…

,

Django

Filter DateTimeField Models with Date format in Django

24 Feb , 2012  

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  |          
........

More…

,

Django

How to convert queryset models into list in Django

23 Feb , 2012  

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")

More…

,

library

Learning property getter setter in Python

21 Feb , 2012  

Property is new feature started in Python 2.2. It have great function to return attribute property when class derived from object. For example :

1
2
3
4
5
6
7
8
9
10
11
class Insurance(object):
    def __init__(self):
        self.name = None
        print(self.name)

    def set_name(self):
        self.name = 'Popel'
        return self.name

a = Insurance()
print(a.set_name())
1
2
print(a.set_name())
# will print "Popel"

To get self.name, we should call method inside derived class, a.set_name().
Then how to change it into attribute ? This why we should know property.

Let see :

1
2
3
4
5
6
7
8
9
10
11
12
class Insurance(object):
    def __init__(self):
        self.name = None
        print(self.name)

    @property
    def set_name(self):
        self.name = 'Popel'
        return self.name

a = Insurance()
print(a.set_name)

We see that when Insurance() initialized, self.name contain “None”. By using property, we can create attribute called “set_name” and make self.name value into “Popel”.

1
2
print(a.set_name)
# will print "Popel"

Property is great feature in Python that developer should know :)

Django

Send content file from FileField Django models via XMLRPC

21 Feb , 2012  

Common cases, we need to send content file from FileField from django models via XML-RPC. In this example, I use django-xmlrpc to handle XMLRPC server. First, we have models :

1
2
3
4
from django.db import models

class Insurance(models.Model):
    file = models.FileField()

More…

,

Django

Marshal Django Models or QuerySet into dictionary and send via Django-XMLRPC

21 Feb , 2012  

Django-XMLRPC provides quick way for build communication between django as server and client via XMLRPC. Some usual cases in using Django-XMLRPC is send dictionaries data into client. We need to convert Models / QuerySet in Django into dict or list.

Luckly, Django have built-in function to convert models into dictionaries (recursive) called “model_to_dict”.
Example usage :

1
2
3
4
from django.forms.models import model_to_dict

insurance = Insurance.objects.get(id=arg)
dict_insurance = model_to_dict(insurance)

More…

,

Django

coercing to Unicode: need string or buffer, FieldFile found Django

21 Feb , 2012  

When I try to send Content File in Django, I got this error :

1
2
xmlrpclib.Fault: <fault 1: "<type 'exceptions.TypeError'>:coercing to Unicode: need string or buffer, FieldFile found">
</fault>

Then i suddenly that making a dumb mistake. Watch this codes :
More…

,

Django

Filter queryset child models related by parent models in Django

21 Feb , 2012  

As I explained in Django query get parent related models from the child models, we can made query parent models from child models relationship.

Now, we will doing filter queryset of child models by parent models value. Given models example :

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=255)


class Insurance(models.Model):
    company = models.ForeignKey(Company)
    package = models.IntegerField(max_length=255)


class Client(models.Model):
    insurance = models.ForeignKey(Insurance)

More…

,

Django

Django query get parent related models from the child models

21 Feb , 2012  

Get parent models queried from child models in Django is possible and easy. For example, we have this parent – child models relation :

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=255)


class Insurance(models.Model):
    company = models.ForeignKey(Company)
    package = models.IntegerField(max_length=255)


class Client(models.Model):
    insurance = models.ForeignKey(Insurance)

More…

,

Django

Solve retrieve file name Django fileField with file.name that show full path

20 Feb , 2012  

When working with Django FileField, you usually need to retrieve filename with file.name. But, when you make query file.name, instead you got full path of filename. This is annoying, right?

We can use templatetags to get basename of file.name by :

1. Create folder templatetags that contains __init__.py and filename.py

1
2
3
4
5
APPS
  |
  |__ templatetags
            |___ __init__.py
            |___ filename.py

More…

,

Django

Convert received datetime instance from XMLRPC server with datetime format in Python

17 Feb , 2012  

This is commonly happen when you have Client or Server send datetime format through XML-RPC. Basically, you can’t use datetime format from received XML-RPC directly, because it have instance type, not datetime format. Also, this is why you can’t save datetime value from XML-RPC directly into Django Models because it need datetime format.

Basically, datetime instance from XML-RPC can be converted into string. Then, it will show up as UTC format which we can convert it later into datetime format.
More…

,

Android

Example Create Simple List View / ListView in Android

16 Feb , 2012  

You better know about ListView while start learning Android. ListView will widely use in Android Development because scrollable of data is commonly used in creating applications. To use ListView, we should extends “ListActivity” rather than “Activity”. Basically, ListActivity is extending “Activity” to handle List of View.

Another keyword while using ListView is called “Adapter”. ListAdapter is used to managing data in ListView. So, when you create a list and you need to customize content / change design in rows of list, then you should use ListAdapter.

Now, create an Android Project. I create activity1.java in Apps -> Src -> App.NameSpace :
More…

,

php

Solve Uncaught exception ‘Zend_Json_Exception’ with message ‘Decoding failed: Syntax error

15 Feb , 2012  

Using Zend_JSON for parse invalid JSON format like “pain in the neck”. If you got this kind of error while parse JSON :

1
Uncaught exception 'Zend_Json_Exception' with message 'Decoding failed: Syntax error

Or maybe :

1
Uncaught exception 'Zend_Json_Exception' with message 'Decoding failed: Unexpected control character found

I suggest to you, move into json_decode() from native PHP. Here are snippets to handle JSON invalid format exception.
More…

, ,

Java

Example parse nested JSON array and Object Java

14 Feb , 2012  

Parsing JSON in Java is same as with another language, but a little bit complex. I use JSON-Simple for parsing JSON and accessing nested JSON array and Object. For example, I have JSON nested structure like :

1
2
3
4
5
6
7
8
{
  "items": [
    {
      "kind": "shopping#product",
      "id": "tag:google.com,2010:shopping/products/10048/187970250782485989",
      "product": {
          "country": "US",
          "language": "en",

More…

,

Java

How to add / import / load JAR into Java project in Eclipse using Build Path

14 Feb , 2012  

Importing JAR / Modules in Java is a little bit different with Python / PHP / Ruby or another programming. In Java, IDE will handle all we need, for instance Eclipse. When we have custom modules like Json Simple Parser and need to add into our Java Project, then we should follow the right path to do it.

Build Path is the main keyword that will explain to us about importing modules in Java. When create Java project and need to import external modules, we need to using Build Path.

For instance :

1. Open Eclipse and create new Java Project called “json”.
More…

,

Server

How to open PostgreSQL remote access with IP address limitation on Ubuntu

14 Feb , 2012  

When trying to configure postgresql to be able accessed remotely from another IP address, we usually got several errors like this :

1
2
3
4
postgresql remote access no pg_hba.conf entry for host

psql: FATAL:  no pg_hba.conf entry for host "xxxxx", user "xx", database "xxxx", SSL on
FATAL:  no pg_hba.conf entry for host "xxxx", user "xx", database "xxx", SSL off

OR

1
" FATAL: no pg_hba.conf entry for host"

To make PostgreSQL in Ubuntu 11.10 can be accessed from remote, follow this path :

Edit this files :

1
sudo vim /etc/postgresql/9.1/main/postgresql.conf

Line 59:

1
listen_addresses = '*'          # what IP address(es) to listen on;

More…

,

Django

Generate PDF with XHTML2PDF Pisa in Django Examples

13 Feb , 2012  

Generating PDF using XHTML2PDF pisa in Django is pretty easy. Here are example / cases how to generate PDF in Django. First things to do is installing XHTML2PDF and PIL with Zlib support.

In this example, we will generate templates/app/test.html.
More…

,

configuration

How to change font bold style of php HTML in Aptana Studio

11 Feb , 2012  

When opening HTML, CTP or another PHP-HTML files in Aptana Studio 3, i found that all using bold which is annoying for me. So, to make it to be normal fonts :

1. Go to Aptana Studio menu -> “Window Menu”

2. Type “Themes” on left search box.

3. Find element “text.html.basic” and change it “Bold” style by click it.

4. Problem solved!

,

Django

How to load images files style css in pdf using pisa xhtml2pdf on Django

10 Feb , 2012  

This problem is widely affected by many developer that use pisa xhtml2pdf with Django. Usually, they failed to load images and styles into pdf using Django templates. There are two posibilites here why this is happen.

1. Incorrect of generate PDF without include resources
We should pointing our resource (STATIC and MEDIA) path into link_resource while generating PDF using xhtml2pdf pisa.
To ease our development, we can use utility that created by pisa creator. Django-Xhtml2PDF utility :
https://github.com/chrisglass/django-xhtml2pdf/blob/master/django_xhtml2pdf/utils.py

But, you should patch it “utils.py” (I already submit pull request and waiting) to make it works by :
More…

,

function

Regex match / search list of word by separate spaces, number, words with spaces using Python

9 Feb , 2012  

This is example of using re module for building regex. Searching match words that contains spaces or separate with spaces or more than one spaces and number. This is most basic things that may faced in daily development. First, let’s create sample text, eg :
More…

,

Django

Solve media directory and URL not found in Django

9 Feb , 2012  

Un-detected / not found media files folder in Django using development webserver is commonly happen in Django pitfalls.
When configure media directory / folder in Django, you should watch several things to make it loaded properly. Miss-configure of media in Django will lead you into Error media files or not found. So, basically, media folder placed in PROJECT_PATH.

1
2
3
4
5
6
7
PROJECT
  |____ APPS
  |____ STATIC
  |____ MEDIA
  |____ urls.py
  |____ manage.py
  |____ settings.py

More…

,

engine

How to enable TOR open for remote access with Polipo on Ubuntu

9 Feb , 2012  

Tor usually installed and running on 127.0.0.1 port 9050 which it’s can’t be accessed from outside. We can open this local listen address TOR signed into IP network and run as HTTP Proxy with Polipo. FYI, I use Vagrant and running Ubuntu Oneiric on Guest. I install TOR in Vagrant guest and accessed it remote from Host (Ubuntu). Let we start with installing tor and polipo on Ubuntu :

1
sudo apt-get install tor polipo nmap

After this installation, TOR should be running on localhost 9050. You can check it by scan using :
More…

,

Django

How to configure and enable Logging / logger in Django for MySQL Database Query

8 Feb , 2012  

We can see what query made by Django by configure and enable logger. Logger in Django is using python logging, so it will have same rule level. We should use “Debug” mode to log and watch query database into our django server development.
Then we can start by editing settings.py :
More…

,

engine

How to login into HPCloud Instance and edit Security Group using Hybridfox

7 Feb , 2012  

Hybridfox is great tools for connecting with our cloud server. When you configure HPCloud server, then you should have this for manage your security groups and allowing several ports to be open. Because default group in HPCloud only allowing SSH port only.

I use the latest Firefox (10 and always updated through update-manager). Then you should download add-on for hybridfox and remember to pick the correct version ” hybridfox-1.6.000112.xpi ” on http://code.google.com/p/hybridfox/downloads/list. Using another version may give error results.

Download and use “Open file” in Firefox to install this add-on. You should restart your Firefox and on “Tools” menu, you should see “HybridFox”. Don’t open it yet, because it will show pop-up. If you have, then you should cancel all confirmation box pop-up by Hybridfox.

Go to your HPCloud, Go to “Account” and select API Keys. I have two region here, but I pick the first one for example. Show access key and secret key “EC2 Compability” :

You should copy this both key into your text editor. Because when you open HybridFox, you can’t switch window.

Then open you Hybridfox, click on Region to add AZ-.

For instance, I add :

1
https://az-1.region-a.geo-1.ec2-compute.hpcloudsvc.com/services/Cloud/

Now, you can add your instance by click on Credentials :

You can insert your access key and secret key.

After connecting, go to Security Group
Go to “Group permission” and click on check(V). Then you can fill it with what kind of port you will open for.

,

Android

Relation between activity, xml, views, intent and layout in Android

7 Feb , 2012  

As a new guy, Android looks like simple if we already have know how the relation between components. From my friends who Android Developer, he said there are 3 important components in building Android applications :

1. Activity
2. Services
3. Intent
4. View

But for now, we will learn about corelation between activity, xml and layout.

First, we will learn about how Activity works. Activity located in /src//activity.java. Activity is single and be responsible to creating window, float and how to put window in UI. Remember, there could be more than one activity in this folder.
More…

, , , ,

Server

Awk sed total bot access.log Apache Ubuntu

6 Feb , 2012  

We can mining and calculate Bot from access.log Apache2 using awk and sed. To get rank and total list of Bot that visit our webpages, then go to “/var/log/apache2″ and this scripts :

1
awk '{print $12}' access.log.1 | sort | uniq -c | sort -nr

More…

,

Django

Alternate or Shortcut way for get object DoesnotExist in Django

6 Feb , 2012  

Although this pretty documented in Django, but most of people still searching a way to make get() more short. So, usually people use get() and DoesNotExist() for searching models. Eg:

1
2
3
4
5
6
7
from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404

But, we can make it more simple by using “get_object_or_404″ :
More…

,

Server

How to create user postgresql using Pgadmin Ubuntu

6 Feb , 2012  

Create postgresql new user using Pgadmin in Ubuntu is very easy. First, launch your Pgadmin that used “postgres” account and connect into localhost. Then, after login, expand your “localhost” item and find “Login Roles“.

Right click on “Login Roles”. Then create your users and setup the permission.

,

Server

How to reset postgres password in PostgreSQL Ubuntu 11.10 Oneiric

6 Feb , 2012  

Reset postgres user password in PostgreSQL Ubuntu 11.10 Oneiric is very simple. First, make sure you have set trust mode in pg_hba.conf ( /etc/postgresql/9.1/main/pg_hba.conf ), for instance :

1
2
3
4
5
6
local   all             postgres                                trust

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust

More…

,

Android

How to example create list view layout in Android

6 Feb , 2012  

Today I will show you how to create simple list view in Android. I assume you already have “Hello World” projects. FYI, there are several Layout Views type in Android like :
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View

For futhermore explanation of this Layout, you go here. Now, we will learn about how to use List View.

First, open your activity files, eg : HelloWorldActivity.java (helloworld/src/helloworld.namespace/HelloWorldActivity.java).
More…

,