Django Tips & Tricks #6 - Make Deleting Easy In Admin

Lets say we have a model as shown in some project.
from django.db import models

class Resource(models.Model):
"""
Model to hold resources for books.
"""
book = models.ForeignKey('Book')
book_type = models.IntegerField()
url = models.URLField()
This model can be registered in admin as follows.
from django.contrib import admin

from . import models

class ResourceAdmin(admin.ModelAdmin):
list_display = ('book', 'book_type', 'url')


admin.site.register(models.Resource, ResourceAdmin)
This will generate a nice admin interface to modify the data.
django-admin-delete
Now if we want to delete a record, we need to follow these steps.
  • First, we have to select that record
  • Next, we have to click on the action dropdown
  • Next, we have to select delete action
  • Next, we have to click Go button.
  • In the next page we have to confirm that we have to delete.
Just to delete a single record, we have to click 5 times. That's too many clicks for a single action.
To simplify the process, we can have simple delete button for the objects as shown. This can be achieved by writing a function which will insert delete button for every record.
from django.contrib import admin

from . import models


class ResourceAdmin(admin.ModelAdmin):
def delete(self, obj):
return '<input type="button" value="Delete" onclick="location.href=\'%s/delete/\'" />'.format(obj.pk)

delete.allow_tags = True
delete.short_description = 'Delete object'

list_display = ('book', 'book_type', 'url', 'delete')


admin.site.register(models.Book)
Now we have an admin with delete button for the records.
django-admin-delete
To delete an object, just click on delete button and then confirm to delete it. Now, we are deleting objects with just 2 clicks.

Read more django tips.
Read more posts about django.

Auto Convert & Upload Books To Kindle

I have ebooks in various formats like pdf, epub, mobi e.t.c. If I want to read books in laptop, I could use ebook reader like Calibre which can open supports most of the formats.
If I have to read them on Kindle paperwhite, it becomes a problem as it supports only few formats. So whenever I get an ebook, I have to convert it to mobi format and send it to kindle.
I can connect kindle to laptop via USB cable and I can copy books. I can also send books to kindle via email.
I found an IFTTT recipe, to automate all this process. I just need to create a folder to store all the books in dropbox. Then use IFTTT recipe to link dropbox folder which has books and gmail to send books to kindle email.
Now when I move required books into dropbox folder in my laptop, they will automatically appear in my kinde.

Automate Boring Stuff - Accepting Waitlist RSVPs

Meetup.com makes it easier to organize events. Before meetup you can specify how many people you can accomodate. Then you send mail to all people so that interested people can RSVP.
If RSVP is full, people can join waitlist. So if somebody changes RSVP to No, we can accomodate people in waitlist.
On the otherhand, if you find a place where you can accomodate more number than you have planned, you can accept all people in waitlist.
Unfortunately, there is no option in meetup for that. You have to accept people one by one which is a boring job if there are ~50 people in waitlist.
This where Python comes to rescue. Python has an excellent package called pyautogui which helps you to automate all boring tasks.
Here is the simple script I have used for this task.
import time

import pyautogui


print('Goto meetup event page and place cursor...')
time.sleep(5)

x, y = pyautogui.position()

for i in range(100):
pyautogui.click(x, y)
time.sleep(5)
The code is self explanatory. First we are importing pyautogui and then wait for 5 seconds so that we can go to meetup page and point mouse correctly. Get the cursor position and start clicking on that position with a gap of 5 seconds. This gap is needed as meetup shows a notification once you accept  RSVP.
Pyautogui is an interesting package which makes your boring job easier.
Update:
Just found that increasing Attendee limit auto changes RSVP of waitlist people to Yes.

Read more articles about Python!

Dropbox As Wormhole Between Ubuntu & Google Drive!

I use Ubuntu on multiple computers everyday. It is important to keep various files synced across them. I keep most of the public data in github repositories and it is very easy to sync across multiple machines.
Google Drive gives 15GB of space with free account. I have multiple accounts and that space is enough to backup my data. I have been storing lots of files in Google Drive from past few years. The main problem is that Google Drive doesn't have a Linux client. To add files, I need to open a web page and then select files to upload and wait until its done. There are few 3rd party clients and none of them work well. So, it is very difficult to sync them across multiple computers.
Dropbox gives 5GB of space with free account. It has Linux client and it works very well. But 5GB of space is not sufficient to store my data.
It is quite difficult to pick one among them as I need benefits of both for free.
Even though I have lot of data, I dont want all of it to sync to all computers everyday. Nearly 90% of data is just backup. Only 10% of data needs to be synced between multiple computers. So I decided to use dropbox as a frontend to google drive.
I have created 2 folders, say Daily & Backup in Dropbox.
Whatever I add to Daily folder will be in Dropbox and it will sync across multiple machines.
There is an amazing service called IFTTT which will help you to connect two products/apps. I found a IFTTT recipe which will add dropbox files in one folder to Google drive.
I have connected Backup folder in Dropbox to Google Drive. Whenever I add a file to Backup folder in Dropbox, it gets added to Google Drive. Once in a week, I will delete files in Backup directory so that Dropbox won't run out of space. So Backup folder will serve as a wormhole to transfer files into Google Drive from my system.

Since I have multiple Google accounts, I have created multiple folders in Dropbox and all folders will be synced to corresponding Google Drive folders.
This setup works well for me as I have Dropbox's Linux client and sufficient storage to backup data to Google Drive.

Book Review - A Psycho Path By Haris Ibrahim K. V.

I stumbled on haris blog and I am thrilled to find that he wrote a book called A Psycho Path. Since ebook was free, I downloaded it and started reading.
I skipped ForewardPreface and skimmed through the first story Etsuko’s picnic.
The second story in the book is A surprising blood test. The story is quite impressive and it hooked me in. Before that story I was lying on the bed and reading. After reading it I got up, sat properly and started reading. Among all the stories, I liked it the most.
Sound relations is another article which I found very fascinating. I read the article many times... 10 times? 20 times? may be more. Long before reading the book, me & my friends had a similar discussion while discussing about impact of music. This article gave an interesting conclusion to our discussion.
Narration of Quito San is interesting.
The book has ~20 stories/articles. Most stories are short stories(2-4 pages). The Prophecy of Amelyah and Quito San are medium sized stories(~20 pages).
Overall the book is very good.
I got a print book after reading ebook. I would recommend getting a get print book from Pothi or Amazon. You can also download free ebook here.

PyCon India 2015 - First PyCon Experience!

PyCon India 2015 was my first PyCon as an attendee, speaker & volunteer.

When I first heard about PyCon in BangPypers meetup, I thought PyCon India is just like a big meetup with a little bit of planning & preparation. But by the end of conference, I have realised that organising PyCon is a very very huge task. It needs a great deal of preparation, planning up things and dedicated volunteers who are interested and patient enough to spend lots of time to run it.

Nicholas Tollervey was keynote speaker. He came to venue on October 1st(two days before conference) and helped volunteers with some tasks. He did the same on next day too. I was wondering whether he came for key note speaking or volunteering.

I have been talking to many people on mailing lists, github and other channels. Finally I was able to meet & talk with many of them in person.

I was not able to attend all sessions but many people said this


It was good to see some of 2nd & 3rd year B.Tech students, who were familiar with django & were contributing to many upstream packages. Some students were even using Emacs as their editor.

Toddlers were also interested to attend PyCon



I have planned to make Python logo mosaic with rubik cubes. I thought it will take ~10 hours to complete it. When I got there with cubes, Vignesh U, Apoorva, Ram Mohan, Sayan Chowday and many other volunteers came forward and completed it in an hour.




I was eagerly waiting for PyCon India from past few months. PyCon India was just like a cool breeze! Ah...!!

Update:

How the hell did I forget about swag kit marathon?

Day before conference, we had to prepare swag kits for participants. I don't know whose idea it was to prepare it like this, that but it was brilliant and most fun part.



Set Emacs As Default File Manager In Ubuntu!

In this post, lets see how to do this


I am using Ubuntu and it has nautilus as default file manager. You might need to use some other commands based on your OS.

File Manager:

If you are in terminal, to open file manager, you need to run nautilus. If you want to open file manager in specific folder, you can run nautilus /foo/bar
When you have downloaded some files using browser, if you click Show in folder in downloads page, it will open nautilus with that specific folder.
We can also make Emacs to act as file manager in dired mode. If you run
$ emacs -q --eval '(dired "~")'
In terminal, emacs starts with a dired buffer for loggined user home directory.
Now lets write a small bash script to do the same thing.
#!/bin/bash
#!/usr/bin/bash
if [ $# -gt 0 ]; then
dirname=$1
else
dirname=$HOME
fi
emacsclient -c -eval "(dired \"$dirname\")" > /dev/null
Save this file as emacsfm in /usr/local/bin. Now you can run emacsfm in terminal which open home dired buffer or you can run emacsfm /foo/bar which will open /foo/bar dired buffer.
Now lets set, emacsfm as default file manager. For that first we need to install exo-utils.
$ sudo apt-get install exo-utils
and run it
$ exo-preferred-applications
It opens a new window like this.
Go to Utilities -> File manager, select Other and goto /usr/local/bin and select emacsfm from it.
Now if you go to browser downloads and click on show in folder, it will emacs dired.

References:

[Python] Functions, Methods & Attributes!

First, lets take a look at functions & methods and then define attributes for them.

Functions Vs Methods:

In [2]: def f():
...: pass
...:

In [3]: class C:
...: def m(self):
...: pass
...:
We have just defined a function and a class(with a method in it).
In [18]: type(f)
Out[18]: function

In [19]: type(C.m)
Out[19]: function

In [20]: type(C().m)
Out[20]: method

In [21]: set(dir(C().m)) - set(dir(f))
Out[21]: {'__func__', '__self__'}
As seen above, a function binded to an instance of a class is method and an unbound method is a just a function. Also a method has __self__ and __func__ attributes in addition attributes of a function.

Attributes:

Lets add some attributes to function & method and see how they work.
In [21]: setattr(f, 'state', 1)

In [22]: hasattr(f, 'state')
Out[22]: True

In [24]: getattr(f, 'state')
Out[24]: 1
We can do the same thing with unbound method(which is nothing but a function) also
In [31]: setattr(C.m, 'state', 2)

In [32]: hasattr(C.m, 'state')
Out[32]: True

In [33]: getattr(C.m, 'state')
Out[33]: 2
But we cant do the same thing with bound methods.
In [34]: setattr(C().m, 'state', 3)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-34-1379e94f2f48> in <module>()
----> 1 setattr(C().m, 'state', 2)

AttributeError: 'method' object has no attribute 'state'
When users add attributes to a function, they are stored in its __dict__ attribute.
In [40]: f.__dict__
Out[40]: {'state': 1}

In [49]: C.m.__dict__
Out[49]: {'state': 2}
As we have seen in the beginning, method objects just hold reference to its class(__self__) and function(__func__). But they don't have its own __dict__ to hold custom attributes. So we cannot set custom attributes to instance methods.
But we can get the function that is referenced by bound method and set attribute for it.
In [36]: setattr(C().m.__func__, 'state', 3)

In [39]: getattr(C().m.__func__, 'state')
Out[39]: 3
Also methods provide, special __getattr__ which forwards attribute access to function object. So, this will work
In [52]: hasattr(C().m, 'state')
Out[52]: True

In [53]: getattr(C().m, 'state')
Out[53]: 3
So we can just set attributes to functions & unbound methods just like classes but we can't do it for bound methods.

Django Tips & Tricks #5 - Use for...empty in Django templates

It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.
{% if books %}
{% for book in books %}
<li>{{ book }}</li>
{% endfor %}
{% else %}
<li>Sorry, there are no books.</li>
{% endif %}
Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as
{% for book in books %}
<li>{{ book }}</li>
{% empty %}
<li>Sorry, there are no books.</li>
{% endfor %}
This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)
Reference: Django docs