Latest Entries Singapore: Introduction to SPA with AngularJS

talk_jsRelated to my target to reach 40pts geek number, I joined several meetup groups in here, one of them is Singapore JS. Honestly, this is quite out of my comfort zone. I am best-known as backend-end software engineer, dealing alot with Python, eventhough I adequately know about HTML, Javascript and CSS, but they are not my strongest points….yet. So it really is a challenge for me.

After about 4 weeks attending book club weekly event from this group, the organizer mentioned about its monthly event, talk.js. And he offered me, and the other guys, to give a talk there. Still worried about  my lack of experience in Javascript, so I said, “All right, count me in!”.

Luckily, I’ve been trying to learn AngularJS for the past week, and I’d like to talk about it, share my experience.

So there I was, on July 1st 2013 @ 19.45, I gave my first talk ever, talking about AngularJS. This slide is made purely on my 2 weeks experience using AngularJS, and I’m sure there’s a lot of improvement can be made. But here it is, one of my many ‘first-time’ moments: Introduction to SPA with AngularJS @ talk.js Singapore.

By Riki Pribadi

Reducing Number of Queries in Django Formset

Using Django Formset is very easy. In my case, I was using model formset to edit a route record together with its segments. Everything looks good until I realize my queries jump quite high. For example, if I have a route that has 50 segments, then I will have additional 50 queries other than my usual queries.



I realize that in Segment model, there’s a field, named flyable_altitude which is a foreign key to another model, named FlyableAltitude, so the reason why I have those extra 50 queries is because every time I render SegmentForm from the formset, field flyable_altitude will read its options(choices) from database. So, 50 SegmentForm to render means, 50 additional queries to execute.

So let’s try a simpler example. Let’s say we have 2 models, Book & BookCategory. Book has a field, named category, which is a foreign key to BookCategory. This is how they look like:

# books/
from django.db import models
class BookCategory(models.Model):
    name = models.CharField(max_length=100)
    def __unicode__(self):
class Book(models.Model):
    title = models.CharField(max_length=255)
    category = models.ForeignKey(BookCategory)
    def __unicode__(self):
        return self.title

And then, let’s say we have an edit page, which will be used to edit all books at once, using modelformset_factory.

Let’s take a step back for now. When field category is rendered, it is rendered as ModelChoiceField, which is an extension of ChoiceField. In the end, what really matters is the choices property value. ModelChoiceField provides 2 ways to construct choices, one is from the queryset, and the other one is by providing the choices manually. And to reduce the number of query, like it or not, we must provide the choices manually. So how can we provide choices for each form in formset?


We can overide _construct_forms method in the BaseModelFormSet, which will provide an extra argument before constructing each form.

# books/
from django.forms import ModelForm
from django.forms.models import BaseModelFormSet
from books.models import Book, BookCategory
class BookBaseFormSet(BaseModelFormSet):
    def _construct_forms(self):
        # Additional arguments to be supplied for each form
        kwargs = {
            'category_choices': [(, for c in BookCategory.objects.all()],
        self.forms = []
        for i in xrange(min(self.total_form_count(), self.absolute_max)):
            # Construct each form with extra arguments
            self.forms.append(self._construct_form(i, **kwargs))
class BookForm(ModelForm):
    class Meta:
        model = Book
    def __init__(self, *args, **kwargs):
        # Always take out 'category_choices' from kwargs
        category_choices = kwargs.pop('category_choices', None)
        super(BookForm, self).__init__(*args, **kwargs)
        # If choices for category is provided, use that value as choices
        if category_choices:
            self.fields['category'].choices = category_choices

After that, I can create the formset factory, and provide its formset & form value. By the way, model formset will render its forms from the queryset parameter, if provided. If not, model formset will take the queryset from model parameter (WhatEverTheModelIs.objects.all()). In this case, I provide the queryset from Book.objects.all()

# books/
from django.forms.models import modelformset_factory
from django.shortcuts import render, redirect
from books.models import Book
from books.forms import BookForm, BookBaseFormSet
def save(request):
    # Use BookForm as the form and BookBaseFormSet as the formset
    BookFormSet = modelformset_factory(Book,
    queryset = Book.objects.all()
    if request.method == 'POST':
        formset = BookFormSet(request.POST, queryset=queryset)
        if formset.is_valid():
            return redirect("book:index")
        formset = BookFormSet(queryset=queryset)
    context = {
        'formset': formset,
    return render(request, 'books/save.html', context)

So now, even if I have 100 books to edit at once, Django will only read the value of BookCategory in database once.

By Riki Pribadi

My Github Project: Responsive CSS

Finally, I published my first Github project to public, Responsive CSS.

What is Responsive CSS?

Responsive CSS is a set of utility CSS classes for responsive web design (adopted from Twitter Bootstrap). It introduces 5 screen size categories:

  • Large Screen
  • Tablet Landscape
  • Tablet Portrait
  • Phone Landscape
  • Phone Portrait

In common case, you have an index page, that will display, for example, list of user. This list has 5 columns: username. full name, email, phone and address. Normally, if you are viewing this index page in normal monitor, you’ll be able to see all of its columns. But what happen when you are viewing this page from smartphone? You might wanna show just the most 2 important columns, like username and full name.

This is where Responsive CSS can help you.

How can I use it?


By using CSS media query implemented by Responsive CSS, you can apply  special CSS classes to your HTML element. So for our previous case, you can solve it like this:

      <th class='hidden-below-tablet-portrait'>Email</th>
      <th class='hidden-below-tablet-landscape'>Phone</th>
      <th class='hidden-below-large-screen'>Address</th>
    {% for user in user_list %}
      <td>{{ user.fullname }}</td>
      <td>{{ user.username }}</td>
      <td class='hidden-below-tablet-portrait'>{{ }}</td>
      <td class='hidden-below-tablet-landscape'>{{ }}</td>
      <td class='hidden-below-large-screen'>{{ user.address }}</td>
    {% endfor %}

Where can I find out more?

To find out more about this project, please visit my Github.

Happy coding!

By Riki Pribadi

Next Target: To Reach 40pts Geek Number

It intrigues me a lot when I read this article, “What’s Your Geek Number? My Points System To Rate Software Engineers”, written by Dave Fecak.

I am a software engineer and I want to market myself better. I had always believed that I was among those highlighted software engineers with great qualifications; worked in prestigious industry & technology, promoted to work abroad at the head quarter,  proven track record, hold important role as team leader & software analyst.

But now, I realize that I was wrong…I have been badly misled. I’m not that outstanding at all! Duh!!

So Dave has compiled a points system with an assigned value for each characteristic. Some of them are positive value, and some of them are negative value. By that, you can count your total geek number. It seems, he will only consider your application if your total geek number is more than 20 though. So if somehow if you got less than that….well…you better do something about it. Continue reading…

Emmet & zen-coding-django-snippets

Yesterday, I was reading this post from Smashing Magazine:  Goodbye, Zen Coding. Hello, Emmet! . Basically it’s a plugin to improve your productivity in writing  HTML-related language. It’s awesome because when I type something like this in my editor (I’m using Eclipse Juno):


Then press tab with my cursor right at the end of it, it’s transformed into this:

<!doctype html>
<html lang="en">
    <meta charset="UTF-8" />
    <div class="container">
        <div class="content">

Simply awesome.

I’m a Django user, so I want to integrate zen-coding-django-snippets into this. But it was built for Zen Coding (even though Emmet was Zen Coding), but it won’t work in my Eclipse. After looking at how it works, I figured that it’s only a matter of context value in the snippet file. Zen Coding is registered under ru.zencoding.eclipse.templates.html name, meanwhile, Emmet is under io.emmet.eclipse.templates.html name.

So I download the original xml file, and simply Find & Replace it. Find ‘ru.zencoding.eclipse.templates.html’ and replace it with ‘io.emmet.eclipse.templates.html’ then imported as usual.  And voila, it works like a charm.


Will be transformed into:

    {% load %}
    <!doctype html>
    <html lang="en">
        <meta charset="UTF-8" />
        <div class="container">
            <div class="content">
                    {% for in %}
                    {% endfor %}

By Riki Pribadi

Django Form Tips: Exclude & Extra Field

I was stumbled before, trying to solve a problem with extra fields in Django forms. The idea was simple, I have a model, then I create a form from that model. But in this form, I need to add extra field to be used to calculate something for model field later on.

To simulate the problem, let say I have a BookModel like below:

class BookModel(models.Model):
    title = models.CharField(max_length=10)
    price = models.DecimalField(max_digits=10, decimal_places=2,
                                help_text="In USD")
    page = models.IntegerField()

And then I create a BookForm from that model like below:

class BookForm(forms.ModelForm):
    class Meta:
        model = BookModel

Nothing strange here yet, right?? We can create an interface using this form so user can save a book record immediately.

One thing to notice, BookModel has a price field and this field is in USD. So let say we want to have another interface to save a book but with another price currency, EUR, for example. Well, you can create a new form without any reference to BookModel, and manage the save-process manually by setting the model fields one-by-one. Or we can just extend the current form to BookEuroForm like below:

class BookEuroForm(forms.ModelForm):
    price_euro = forms.DecimalField(max_digits=10, decimal_places=2,
                                    help_text="In Euro", label="Price")
    class Meta:
        model = BookModel
        exclude = ('price',)

Continue reading…

How to Export PostgreSQL Database to Different Host

A moment ago, I was trying to copy a PostgreSQL database from old server to a new server. It shouldn’t be a problem, right? Let’s say these are the conditions:

  • Old server:
    • address:
    • database name: db_old
    • database user: user_old
  • New Server:
    • address:
    • database name: db_new
    • database user: user_new

So what I did was:

1. Export database from Server to a file. I can do that using this command:

    $ pg_dump -Ft db_old -U user_old > db.tar

Be very careful when using compression though, because -Ft means you’ll compress the file as tar file, and there’s limitation about it. Like stated in the PostgreSQL documentation:

Output a tar-format archive suitable for input into pg_restore. The tar-format is compatible with the directory-format; extracting a tar-format archive produces a valid directory-format archive. However, the tar-format does not support compression and has a limit of 8 GB on the size of individual tables. Also, the relative order of table data items cannot be changed during restore.

So, for a normal backup without any compression:

    $ pg_dump db_old -U user_old > db.sql

2. Import database file to Once I copied the file to this host, I can import the database using this command:

    $ pg_restore -d db_new db.tar -U user_new

And done!

But after more thorough reading, there’s a more convenient way to do that. You can copy the database from one host directly to another host by combining (pipe-ing) previous 2 commands :

    $ pg_dump -Ft db_old -U user_old -h | pg_restore -d db_new -U user_new -h

Or, without compression:

    $ pg_dump db_old -U user_old -h | psql -d db_new -U user_new -h

There! Much simpler!

By Riki Pribadi

Pickle: Python Object Serialization

Before we go any further about pickle , what in the world is serialization ? According to Wiki,

Serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link.

So, now we know what that is. But next question, why do we need this mechanism? For example, I believe you remember ‘saving game’ mechanism in your favorite game. If you look more deeply, it is a serialization . If you still don’t see it then go deeper. Imagine you have a hero object, with map object, and some enemy objects. All of informations of those objects, is saved into a file when you agree to save that game, so next time, when you load that version of game again, it will bring you to the exactly same state.

I think, serialization is a better way and absolutely a better way to save object informations to other medium. Yes, you can do it manually. You can make your own function to save object informations to file, and create a function to read that informations again from file to object. But why so serious ?? With serialization, it’s a very easy thing to do. You don’t need to know how it writes and reads the data. All you need to do is just use this function and it works. That just it. And in Python, that’s where pickle takes place. Continue reading…

Python: ConfigParser – Configuration File

Now, what d’hell is Configuration File?? According to Python Doc , we can make a conclusion that configuration file is:

just another file which provides a structure similar to what you would find on Microsoft Windows INI files, commonly with extension .cfg or .ini, consists of sections, led by a “[section]” header and followed by “name: value” or “name = value” entries with continuations in the style of RFC 822

Config file example:

ip = localhost
port = 9001

engine = mysql
username = test
password = 123
database = test_db

In order to handle this kind of file, Python provides us with ConfigParser library. With this library, reading-writing-modifying configuration file becomes more handy. So please, do not ask me why we just don’t use Python file’s functions. Continue reading…

SelectBox.js for Many-to-Many in Django Admin Panel

many to many

If you ever noticed, when you’re creating a new user in Django admin panel, there’s a permission section which use a very handy javascript plugin for selecting permisions, SelectBox. Basically, this is a multiple select dropdown. But since a bare multiple select dropdown is a nigtmare, you need to hold Ctrl to select more than one, and not to mention, it is very easy to have your selection reset accidentally, God has sent this plugin trough His messenger to end this nightmare. And in Django, they already have it. Ahhh…just another reason why I love Django. Seriously, it is a very easy things to do. But let’s do this step by step from the very beginning. Continue reading…

Copyright © 2015 All rights reserved.

RSS Feed. This blog is proudly powered by Wordpress theme by Rodrigo Galindez.