Photo of Seemant

Seemant's Blog

Apr 16 2007

Building my Django Weblog: Part 3

Categories: , , Filed by: Seemant Kulleen
35 Comments Subscribe to this entry's comments RSS feed Subscribe to this entry's comments Atom feed

One day, while searching for something Django related, I ran into a really nicely done Django weblog. What caught my attention here, is that he came up with a way to spiffy up his comments display by showing a country flag for each commenter. It looks really spiffy. So I decided to play copycat.

Well, it only took a few minutes to implement it in the testing version of my own blog, and I showed it off to a couple of my friends in IRC. One of them, tjfontaine, said something along the lines of “oh neat, libgeoip.” Obviously, I hadn’t seen or heard of this libgeoip thing so I asked him about it and he linked me to it. Now this was interesting, because it comes with python bindings. And the best part, of course, is that it is in portage. So I installed it, and had a look at their usage sample. Essentially, you just download their ip to country map, which they update once a month, and so you don’t have to hit their servers everytime you do a lookup.

Next up, I wrote the templatetag to use GeoIP. In its entirety, it looks like this:

from django.template import Library
import GeoIP

register = Library()

def get_country(value, arg):
    ''' arg is the location of the flag imgs, eg '/media/img/flag/' '''
    try:
        gi = GeoIP.open('/usr/local/share/GeoIP/GeoIP.dat', GeoIP.GEOIP_STANDARD)
        code = gi.country_code_by_addr(value)
        name = gi.country_name_by_addr(value)
    except:
        return " "

    if code:
        img = "%s%s.png" % (arg, code.lower())
        return '<img src="%s" alt="%s" title="%s"/>' % (img, name, name)
    return " "

register.filter('get_country', get_country)

And to use it in a template, you would do something like this:

{% load iptocountry_filter %}
{{ comment.ip_address|get_country:"/media/images/site/flags/" }}

So by switching to this method, I no longer need to have a special Django model to store the ip to country maps (and since I use postgresql, I don’t have to go through the pain of altering any columns or updating my Django database every so often. Instead, I can just set up a monthly cron job to fetch maxmind’s database file and put it on my filesystem. And that is why you see those little flag icons on alll the comments on my site.

The only concern that some people might have is that GeoIP is a GPL-2 application, so there’s a concern that using it might virally make your own code GPL-2. If that is the case, then the above code is licensed under the terms of the GPL-2 as well, so use as you see fit within those terms, I guess. If it is not viral, then let’s say it’s a freebie. Either way, no warranty on it.

The idea is entirely Coulix’s and he deserves all the credit for it.

Permanent Link
Subscribe to this entry's comments RSS feed Subscribe to this entry's comments Atom feed

35 Comments

Australia Comment by coulix after 6 hours, 57 minutes

Nice, very neat.

France Comment by David, biologeek after 1 day, 7 hours

This is only a test, I repeat, only a test :-).

Slovenia Comment by S. after 1 day, 10 hours

Can't resist testing this. :) Excellent job here, Seemant! I knew of you as a Gentoo person, but I didn't know you were a Django person as well! That rocks.

United States Comment by bigboy after 1 day, 16 hours

Cool, looks good ;).

Spain Comment by JC after 2 days, 3 hours

simply irresistible…

hello from sPAIN

Czech Republic Comment by dave after 2 days, 5 hours

Another hello from Czech republic

New Zealand Comment by ryan after 2 days, 8 hours

Greetings from New Zealand

Slovenia Comment by Martin after 3 days, 1 hour

hello, Seemant,

i'm posting this here, because i can't find your contact mail. anyway, there seems to be a problem, because your new post named Building my Django Weblog: Part 4 isn't visible (only visible on rss feed).

Keep up the good work ;) Martin

United States Comment by Seemant Kulleen after 3 days, 1 hour

Hi Martin,

I'm so sorry about that. I was still just writing part 4, so I hadn't intended to publish it just yet. So you found a bug, because I was not filtering out unpublished entries from my feeds :(

I've fixed that (so it should disappear from the feeds), and I'll publish part 4 as soon as it is done.

I'm working on creating a contact form for this site, too.

United States Comment by coolguy after 3 days, 17 hours

looks cool

Canada Comment by Kyle after 4 days, 1 hour

Does this know I'm Belgian?

(In truth, I'm Canadian…)

Italy Comment by Nicola Larosa after 4 days, 13 hours

Another test from Italy. :-) And thanks for this writeup!

United States Comment by cbmeeks after 3 weeks, 1 day

Looks great!

I like the flag addition.

http://www.signaldev.com

Kuwait Comment by Ahmad Alhashemi after 1 month

Great series, Seemant.

You might want to add OpenID to the list of technologies you are learning related to this series.

Also a subtle point. I've noticed in your post that you are querying the GeoIP database during template rendering. I don't know how likely this is to happen, but it might happen that some IP blocks eventually get reassigned to a different ISP in a different country. Since you are querying the database at the time of template display and you are keeping the database updated, an old comment by a person in one country might suddenly change flags and appear to be originating from a different country with the updated database.

On the plus side, a person with a newly assigned IP address that hasn't made it to the last database update might get the correct flag with the next db updated, but this is probably much less likely to happen because the time difference between the comment and the database will be less than one month, but using your way, the time difference will keep increasing for old comments and will probably be years.

United States Comment by Seemant Kulleen after 1 month, 2 weeks

Hi Ahmad,

I've been thinking about your comment for a while. I agree with you — I will change the models to save the country information into the database instead of dynamically looking them up at template rendering time.

And yes, OpenID is definitely on my list of technologies to explore with this blog. With any luck, it'll be within the next few weeks :)

Algeria Comment by me after 2 months, 3 weeks

hi from guess where? :)

Algeria Comment by karim after 2 months, 3 weeks

lovely! simply lovely!

Sweden Comment by zehi after 3 months, 3 weeks

I can't resist to make one brainless comment - cool.

Luxembourg Comment by Laur after 1 year, 10 months

Let's see now :)

Argentina Comment by Virtex after 3 years

Вот про все это я почитал с большим интересом. И прочитал бы еще больше! Планируете и в дальнейшем писать на эту же тему? Спасибо

Poland Comment by Artemstrogov after 3 years

Бесплатный конструктор icq для мобильного: <a href=http://www.aska21.ru/icq-nastroiki.htm>icq для nokia n73 бесплатно</a>

Ukraine Comment by порно ранетки after 3 years, 1 month

Это я уже читал на другом сайте. Досвиданья.

Germany Comment by Immumnsteanty after 3 years, 1 month

Доброго Вам дня, моё имя Денис. Я создаю эффективные логотипы на протяжение 10 лет. 15 марта 2008 года я основал свою фирму — “ADG: Arsentyev Design Group” (http://www.a-d-g.ru). “ADG: Arsentyev Design Group” — Стратегия эффективного дизайна!

*Коммерческое предложение для бизнесменов. Эффективный логотип приумножит доход вашего бизнеса. Стоимость создания эффективного логотипа от $200. Срок создания от 7 дней. Онлайн консультации (ICQ: 162756770. Skype: arsentyev.denis)

*Предложения для рекламных компаний и студий дизайна. Рассмотрю предложения по фрилансу и аутсорсингу.

Посетите мой виртуальный офис http://www.a-d-g.ru и ознакомьтесь с моим портфолио.

Удачного дня и всех благ.

рекламное агентство, лого, логотип, эффективные логотипы, создание логотипов, дизайн, проектирование, дизайнер, графический дизайн, коммерческий дизайн, фирменный стиль, арт-директор, фриланс, фрилансер, аутсортинг, брэнд, брэнды, веб дизайн

Germany Comment by SpuppyAltelve after 3 years, 1 month

Всем, кто имеет доступ к копиям документов об образовании: аттестаты, дипломы ВУЗов, техникумов, академических справок, Вам выпал шанс заработать ничего не делая. Если Вы или Ваши родственники, друзья, подруги, знакомые имеют доступ к учебным планам высших учебных заведений, вы можете зарабатывать от 500 рублей и выше. Все зависит только от Вашего желания.

Контакты istud@list.ru 8-985-972-43-85

Работа, диплом вуза, образец диплома.

Russian Federation Comment by ExhithReeni after 3 years, 1 month

<a href=http://kralin.ru>Услуги адвоката</a> недорого! консультация бесплатно!

Специализируюсь на:

-правовом обслуживании компаний; -ведении уголовных дел различной категории (должностные преступления, преступления в сфере экономики, преступления против личности, против общественной безопасности и порядка, преступления в сфере незаконного оборота наркотиков, оружия и др.); -ведении дел гражданско-правовой специализации в судах общей юрисдикции и арбитраже; -правовая экспертиза сделок по недвижимости, а также с участием агентств по недвижимости.

http://kralin.ru

Russian Federation Comment by Dyerrelprar after 3 years, 1 month

Приглашаю всех в свой блог посвященный МИНИИГРАМ ВСЕ ИГРЫ МОЖНО БЕСПЛАТНО СКАЧАТЬ http://www.liveinternet.ru/users/2932876/blog/

Ukraine Comment by Михаил after 3 years, 1 month

Эээ, а объясните, плиз, а то я че-то не совсем въехал в тему, это как?

Colombia Comment by гoлЬeтти after 3 years, 1 month

Я никогда не сомневался в Ваших интеллектуальных способностях, но поймите, не все такие как Вы. :)

Ukraine Comment by олайн гей ролик after 3 years, 2 months

Даужж никогда не думал об этом …

Russian Federation Comment by Froreequice after 3 years, 2 months

doubles-shop.ru - Интернет магазин прикольных футболок. У нас самые свежие работы дизайнеров, которые не покладая рук придумывают новые рисунки на футболки. Мы сами придумываем и производим свои прикольные майки, которые пришлись по вкусу более чем 100 000 покупателей со всей России. В наших прикольных футболках выступали звезды киберспорта, спортсмены, и д.р. Вы можете ознакомиться с полным прейскурантом футболок на нашем сайте (doubles-shop.ru). Мы специально разбили наши прикольные футболки по разделам для удобства наших пользователей. Закажите футболки с надписями прямо сейчас и мы её доставим Вам Почтой России! Для жителей Москвы и Санкт-Петербурга работает курьерская служба, доставка в течение 10 дней! Если же вы хотите придумать свой дизайн футболки, то у нас действует специальная услуга - футболки на заказ. Для этого необходимо перейти в специальный раздел.

Ждем вас на нашем сайте: http://www.doubles-shop.ru

Colombia Comment by Сопротивление after 3 years, 2 months

Текст реально понравился, особенно здесь последний абзац хорош :)

Ukraine Comment by красивая волосатая пизда after 3 years, 2 months

Даужж никогда не думал об этом …

Spain Comment by XAN after 3 years, 3 months

Мдааа…, а я тут всю жизнь прожил, как-то привык ко всему этому, даже внимания на это не обращаю :) Вы тоже привыкнете :)

Netherlands Comment by sanandogorod.ru after 3 years, 3 months

Тема старая конечно , но прочитал с удовольствием :)

Belarus Comment by Cicstriasse after 3 years, 3 months

Месяц (осьмый 2010. Сообразно государстве проехалась вал презентаций людей, гневных неимением действующих http://bigtorrents.org - игры на компьютер скачать торрент граней сообразно войне с дивыми пожарами. Администрация в ударе: демонстранты, отчего-ведь, никак не опасаются буква аква пушек, буква газа…http://bigtorrents.org - скачать соурс через торрент

Join the conversation