Vinit Kumar

Blog about Web & Programming


© 2014. Vinit Kumar All rights reserved.

How it went?

Hello People!

It has indeed been very long since I last wrote a blog post. It sure feels good to start it again. Firstly, if you enjoy my writing, I am sorry for this big gap. I was very busy in writing code at my work.

Here are some important updates about what happened:

  • I got married! Yay :) I got married in December with my lovely girlfriend. It has been pretty amazing last three months with her.
  • I wrote various features for my product and there are more than 20k users using those features right now and the feedback has been quite good actually.
  • I write less code these days and spend more time thinking. I think it is better this way. I felt burnout with my previous lifestyle. Now, I wait to write code every morning.
  • I feel less annoyed with stupidity around me and have a better coping mechanism.

I have decided to be more consistent with my reading habits. I hope to be more sincere this time. That's it for now. Will write another post soon.

Better Time Management At Work

Time management is a key quality of any successful person. I have been working pretty hard these days to improve me efficiency. Today, I have decided to follow this pattern while at work.

Here is the breakdown. Let's assume the net hour spent at work is 8.

  • 50% Time (4 hrs) - Writing Code.
  • 5% Time (24 min) - Documentation of the Code I wrote.
  • 5% time (24 min) - Writing test on the Code I wrote.
  • 10% time (48 min) - QA and testing the work I produced.
  • 20% time (96 min) - Planning and Studying about the topic I need to work on.
  • 5% Time (24 mins) - Working with colleagues and helping out in case they need any assistance.

I felt the need to this timetable because it is really necessary to control the time when you are on tight deadlines. I like giving my all to the work and definitely have very limited time to execute that. So only if my planning and time management is solid I would be able to produce quality work on time.

I will produce a analysis of how this goes and how much success I achieve using this methodology. Also, today I have completed my 41 day streak at GitHub.

On Writing Good Code

Whether you are working for a big software company or a small sized startup, writing good code is pretty much critical to your success. But the catch is it is not very easy to achieve without proper motivation from your side.

I have been coding professionally for almost 4 years now. First two years were as a freelancer and I mostly followed Get Things Done mode during that time. It was okay then because it was mostly a one time gig and once done you didn't had to do anything with it. Though I never wrote really bad code even at that time but the amount of maturity and knowledge required to write code that is maintainable, DRY and has some documentation was clearly not there.

While I joined my first company back in 2013, I really struggled against my bad habits. I was able to solve tough technical problems as problem solving is always close to my heart but there were serious issues with my code quality. Sometimes there was some indentation issue and something there were some code repetition. I was lucky to have my Mentor "Ruben" to closely look at my code and review it sharply and give his most honest feedback. Upon pondering about the review I realized most of the issues were coming because a certain amount of thinking and carefulness that was missing from my workflow. I didn't had my editor configured properly. Mix of tabs and spaces will obviously come back to bite you and code will look ugly on browser even though it looked fine on your editor. (Sublime Text, I am looking at you).

Now, after almost an year later I am a improved and mature programmer than what I was at this point of time last year. So what changed?

Here is a short summary of things I did in order to get better at writing code:

  • I started reading classic books on programming. Understanding programming and computer science is pretty much vital to your growth as a software developer. Dreaming about making big in this field without having solid basics is a fools errand.
  • Read a lot of good code. Discuss about it, blog about it and finally incorporate those into your own code. This is pretty much most important to improve the code you are writing. I started reading a lot of good code, on an average of 1 hour daily. With loads of Open Source projects available on Github and bitbucket it is pretty easy to do so.
  • Follow strict mode in almost every language your code on. Use Pep-8, JSHINT, CSSLint, Grunt. This might be painful at beginning but it would cover a lot of ground that you might not know as you are not an experienced developer.
  • Learn and use Travis CI and Jenkins system that would automate a lot of these things in your code.
  • Write a lot of code and open source it. Also, contribute to a good number of OSS projects. I have done a lot of this in the past year and believe me it has really helped in improving.
  • Read the f**king documentation - This is kind of most important if you want to really use the power the language or the framework provides. Otherwise, you will keep writing shitty code because you were never aware better way exists.

  • Use version control- Version control gives you an opportunity to look at your code before committing. Use this powerful feature. Always review your code before your commit. Always review a pull request and merge.

How To Get Readonly Mode In Django

Last week, I came across an interesting problem at work. The problem was:

To get read only users in a Django based application.

But doing so was not very simple because there is no read only mode for users in Django. In order to solve this, I first started reading answers on stack overflow. Some of those links did pointed me to a correct route. Here, I will document the whole process so that it could help others and serve as a reminder for me as well.

First of all, the whole system of authentication in any system originates from permissions. The basis permissions are. Read, Write, Execute. in Unix (chmod is used to set permissions).

Django has a cool way of adding the permissions in the meta class. Let's say we have a model class named Cars.

class Cars(model.Model):
  name = models.Charfield()
  year = models.DateField()

  class Meta:
    permissions  = (
      ('readonly', 'Can Read Only Cars')

Just like this, Any permission could be added to the Model. Now in order to get these permissions in the database. You need to run syncdb management command.

python syncdb --all

So this just sets the background in place. The real job is getting this permissions to work.

Now, I began to wonder what all things were required to develop this complete functionality ?

The first thing that came to my mind naturally was to override templates and hack ground

So, I created a new class in that was inherited from the admin class I was earlier using:

from model import Cars

class CarAdmin(admin.ModelAdmin):
    date_hierarchy = 'date'
    list_filter = ('status', 'event_instance',)
    actions = ['accept', 'reject', 'pending']

class ReadonlyCarAdmin(CarAdmin):
    def __init__(self, model, admin_site):
      super(ReadonlyCarAdmin, self).__init__(model, admin_site)
      self.model = model

    def has_delete_permission(self, request, obj=None):
      if request.user.has_perm('car.readonly') and not
        return False
        return True

    def has_add_permission(self, request, obj=None):
      if request.user.has_perm('car.readonly') and not
        return False
        return True

     def has_change_permission(self, request, obj=None):
        if request.user.is_superuser:
            self.readonly_fields = () # make sure to remove caching.
            return True
        elif request.user.has_perm('car.readonly'):
            # make the fields readonly for only users with readonly permissions.
            self.readonly_fields = [ for field in filter(lambda f: not f.auto_created, self.model._meta.fields)]
            return True
            return False

     def get_actions(self, request):
        actions = super(ReadOnlyCarAdmin, self).get_actions(request)
        if request.user.has_perm('car.readonly') and not request.user.is_superuser:
            # This ensures that that user doesn't not have any actions
            if 'delete_selected' in actions:
                del actions['delete_selected']
                del actions['accept']
                del actions['reject']
                del actions['pending']
            return actions
            return actions

admin_site.register(Car, ReadonlyCarAdmin)

Okay, so now we have a robust system in place to ensure whichever user has readonly permission on Cars Model would only be able to see the model data in Readonly mode.

But this is not it. Here is the part where templates are overridden.

First of all save and cancel button on buttom needs to go as we don't need them.

For that, create a new template in templates folder.The templates name is change_form.html. Hence the full pathname is carapp/templates/admin/change_form.html.

Copy the content from the default django template (/admin/change_form.html) in django project add replace this content with this gist:

This will ensure that the selected user with this readonly only permissions won't be able get the submit button on his admin page.

Now, you have a fully functioning Django Admin with readonly mode. The main effort was to make it very easy to use and ensure that this feature could run across future versions.

Hope this post help anyone else who has to implement something similar.

Setting Up Emacs for Development

I always wanted to use Emacs. Yesterday, I wanted to have a good JavaScript/Node REPL in my editor. Though I had always used Vim since last 5 years still setting up a REPL in Vim is not very easy. So I decided to give Emacs a try and till now I am enjoying using Emacs.

Here is a guide that would help you to setup emacs.

First of all, If you are on Mac install emacs for OSX from here. you could easily install the GUI version of Emacs for other platforms too.

My Emacs config

This is my Emacs config which could be used for development in following technologies:

  • Ruby / Ruby on Rails
  • HAML / Markdown / Textile / ERB
  • Clojure (via nrepl)
  • Javascript / Coffeescript
  • Python
  • PHP
  • Haskell
  • Erlang
  • Common Lisp (with Slime)

In particular, there's a nice config for tab autocompletion, and flycheck is used to immediately highlight syntax errors in Ruby, HAML, Python, Javascript, PHP and a number of other languages.


This is my emacs live in action:


  • Emacs 23 or greater (note that Emacs 24 is required for some functionality, and will likely become the minimum required version some time soon.)


To install, clone this repo to ~/.emacs.d, i.e. ensure that the init.el contained in this repo ends up at ~/.emacs.d/init.el:

git clone ~/.emacs.d

Upon starting up Emacs for the first time, further third-party packages will be automatically downloaded and installed.

Adding your own customization

To add your own customization, use M-x customize and/or create a file ~/.emacs.d/lisp/init-local.el which looks like this:

... your code here ...

(provide 'init-local)

Tips for using these emacs settings

If you want to use my settings straight out of the box, here are some things to note:

  • I recommend starting with a blank emacs + Technomancy's better-defaults package, and then dig through this repo for useful nuggets, instead of forking it directly.

  • The key bindings are optimized for a norwegian keyboard layout.

  • Start by reading up on all the cool stuff in key-bindings.el.

  • You quit emacs with C-x r q, mnemonic Really Quit.

  • Find file in project with C-x o, in dir with C-x C-f, recent with C-x f

  • Add your user- and project-specific stuff in .emacs.d/users/[machine name]/*.el

  • C-h is rebound to backspace, like in the shell. Get help on F1 instead.

  • Autocomplete with C-. (autocomplete entire lines with C-:)

  • expand-region is your friend. Find its bound key by doing F1 f er/expand-region

  • Undo with C-_ and redo with M-_. Watch the undo-tree with C-x u

  • Quickly jump anywhere in the buffer with C-ΓΈ then the starting letter of a word.

  • Indent and clean up white space in the entire buffer with C-c n

  • On a mac, the Meta key M is bound to Command.

  • I recommend rebinding Caps Lock to Ctrl and use that instead of the often badly placed Ctrl-key.

  • Watch

Survival guide for the first week of emacs

When you start using emacs for the first time, your habits fight you every inch of the way. Your fingers long for the good old familiar keybindings. Here's an overview of the most commonly used shortcuts to get you through this pain:

  • C Shorthand for the ctrl-key
  • M Shorthand for the meta-key (bound to cmd on my mac settings)
  • S Shorthand for the shift-key


  • C-x C-f Open a file. Starts in the current directory
  • C-x f Open a recently visited file
  • C-x o Open a file in the current project (based on .git ++)
  • C-x C-s Save this file
  • C-x C-w Save as ...
  • C-x C-j Jump to this files' current directory
  • C-x b Switch to another open file (buffer)
  • C-x C-b List all open files (buffers)

Cut copy and paste

  • C-space Start marking stuff. C-g to cancel.
  • C-w Cut (aka kill)
  • C-k Cut till end of line
  • M-w Copy
  • C-y Paste (aka yank)
  • M-y Cycle last paste through previous kills
  • C-x C-y Choose what to paste from previous kills
  • C-@ Mark stuff quickly. Press multiple times


  • C-g Quit out of whatever mess you've gotten yourself into
  • M-x Run a command by name
  • C-. Autocomplete
  • C-_ Undo
  • M-_ Redo
  • C-x u Show the undo-tree
  • C-x m Open magit. It's a magical git interface for emacs


  • C-arrow Move past words/paragraphs
  • C-a Go to start of line
  • C-e Go to end of line
  • M-g M-g Go to line number
  • C-x C-i Go to symbol
  • C-s Search forward. Press C-s again to go further.
  • C-r Search backward. Press C-r again to go further.

Window management

  • C-x 0 Close this window
  • C-x 1 Close other windows
  • C-x 2 Split window horizontally
  • C-x 3 Split window vertically
  • S-arrow Jump to window to the left/right/up/down


  • F1 t Basic tutorial
  • F1 k Help for a keybinding
  • F1 r Emacs' extensive documentation

Credits & Inspiration

This config is totally based on this repo by Mr. Steve Purcell. But this might diverge with time and my personal taste.

The Survival guide has been taken from .emacs.d project of Mr. Magnar Sveen