django: Hacking django object_list to take list of templates

I recently found that you can pass a list or tuple to both django.template.loader.render_to_string and django.shortcuts.render_to_response. These functions iterate over the list of templates and render the first template that exists. The magic lies with the django.template.loader.get_template and select_template functions which take a single template name or list of templates respectively.

This is a great functionality to provide a generic-customized templating architecture where you can pass the name of a specialized template with fallback template name in the last. While working on SeenReport, this feature came really handy as this allowed us to create specialized templates for selected communities with a default template for fallback.

However, I found a slight problem while implementing this architecture. The django.views.generic.list_detail.object_list only accepts a single template name. The solution,

  1. patch the object_list function to use get_template for single template name and select_template for list of templates
  2. find a workaround :)

For reasons beyond the comprehension of common beings, I try not to mess around with django so started looking for a workaround. Going through the definition of object_list, I realized that the object_list receives template_loader as an optional parameter and calls template_loader.get_template to get the passed template. Here is the definition of object_list,

 

def object_list(request, queryset, paginate_by=None, page=None,
        allow_empty=True, template_name=None, template_loader=loader,
        extra_context=None, context_processors=None, template_object_name=’object’,
        mimetype=None):
def object_list(request, queryset, paginate_by=None, page=None,
        allow_empty=True, template_name=None, template_loader=loader,
        extra_context=None, context_processors=None, template_object_name='object',
        mimetype=None):
...
...
    t = template_loader.get_template(template_name)
    return HttpResponse(t.render(c), mimetype=mimetype)
Here is the workaround,
  • pass a list of templates in template_name
  • pass a custom template_loader with a get_template function
Here is the code for my template_loader
def get_template(template_name):
      from django.template import loader
      if type(template_name) == list:
            return loader.select_template(template_name)
      else:
            return loader.get_template(template_name)
The code is self explanatory. If template_name is a list, I call loader.select_template, get_template otherwise. And with that the object_list is seemingly patched to handle list of templates.

SeenReport closes first round of funding

 

SeenReport (Pvt.) Ltd. has successfully closed its first round of investment from Al-Janabi Group (Official press release)

Phew, I had to keep this news secret for so long that I started having stomach problems. Now that its out, I feel much relieved :) . Yaser beat me to the blog post, here is his take on the same news.

With achieving this milestone, SeenReport (Pvt) Ltd has joined a handful of Pakistani startups that have received investment from foreign VCs. A feat for which the whole SeenReport team deserves a thorough congratulations. This is especially great news for our CEO, Sharjeel who can now stop sleeping on the floors to save money on his international trips (also keep his PS2) :D

 

From three computers and some pretty cheap furniture, the path to a multi-million dollar company has been paved with hard work, more hard work, patience, dedication, trust, sleepless nights, depressions and hope. When we started out two years ago, the odds were really stacked against us. Startups are by default very hard, and being in Pakistan during the financial crisis situation only makes the situation more grim. Add the flavors of heavy criticism and stigma of failure and you get a recipe of anti-startup culture. By the grace of God, hard work of the team, prayers of our families, advice of our advisors, dedication of our users and some pure luck, SeenReport has overcome these odds. The selfless help of people like Belal Hashmi, Shafiq-ur-Rehman, Hashim Ali (CEO Mantaq Systems (Pvt.) Ltd.), Mr. Shahid Malik, Rabia Garib and Jehan Ara has really helped us along, for which we are obliged.

However, getting investment neither equals nor guarantees success. In fact it adds responsibility and accountability to the existing (over) burdened shoulders of the founders. SeenReport still has a long way to go in becoming an Organization capable of generating sustained results but I am confident that we are well on our way.  We are now more committed and determined to generate results than ever before.

I meet a lot of entrepreneurs who believe that they have the next big idea and all they need is funding. And since they cant get any funding, they are unsuccessful. Well, we started with one basic rule,

There are no VCs

This made our lives much easier (believe me). We knew that we had to do everything by ourselves, all the money had to come out of our own pockets and all leads generated on our own. So, we put our heads down and focused all our energies in making SeenReport the best platform for social news generation and creating awareness among people about it. The logic was simple, Make something great, achieve results and let the results speak for themselves. This didn’t win us a lot of brownie points among the typical “Write plans, get money, hire someone to make product” theory but it did attract the right people with similar mindset.

I am confident that this news will encourage more young Pakistani entrepreneurs to start their own ventures. VC culture develops because of the new horizons entrepreneurs create, not the other way around. Remember, the most important thing required to change the world is the belief to change the world.

Raising the investment during the on-going financial crisis underlines the faith both SeenReport and Al-Janabi Group have in the SeenReport team and the business model. I would like to welcome Al-Janabi Group to the SeenReport team and feel excited to work together in taking SeenReport to greater heights.

Pakistan Cricket – Snatching defeat from the jaws of victory

Yesterday, Pakistan Cricket team successfully lost a test match to Sri Lanka (details). Pakistan team needed 97 runs to win on the 4th day of the match and successfully lost all wickets for 47 runs. For its wonderful ability to pull a defat from the jaws of the victory, the team deserves a hearty congratulations. This is the closing ceremony of the match for all those who missed it.

Anchor: Younis, it was a surprise performance. The match was all but over and then all of a sudden you guys pulled this match back.

Younis: Yes, it was getting tough as the match went along. Especially on the 4th day, when we needed 97 runs and had 8 wickets, it was really difficult. But credit to the boys, who pulled themselves together and turned the match around to lose it.

Anchor: What was going through your mind when this was happening?

Younis: Honestly speaking, I was never worried. I had complete faith in the boys and knew than we could lose whenever we wanted to. It was all just a matter of time. We waited for the right time to lose wickets and let conditions take care of the rest.

Anchor: What do you think was the turning point of the match?

Younis: The turning point would definitely have to be the Salman Butt’s slash with his eyes closed in the same over when Yousaf departed. At that time, it was looking as if we would definitely win. But then Yousaf fell in the second over of the day and one ball later when Butt got out trying a shot that he used to play at age 5, I knew we were on track to lose the match. After that, I didn’t worry at all, it was just a cruise.

Anchor: What about Yousaf? He made a century in the first innings and you guys took a lead of 50 runs?

Younis: All I can say is that Yousaf has been out of the team for over a year and half so I took him some time to return to normal. However, I was always confident that after a little match practice he would be up with the rest of the boys in no time. Getting a lead was definitely tough but it meant that we had to perform really poor in the last inning, which we eventually did.

Anchor: You guys had just won the T20 World Cup against the same team? Did you say anything special to the team?

Younis: Well I just told them that, hey look, dont take any kind of pressure or responsibility. All we need to do is to play our natural game, don’t care where the ball is pitched, drop any catch that comes your way and wave that bat as if you are doing it for the first time. And I am really glad that they did listen to me. I am sure the victory in the T20 World Cup will soon be behind us and we will be losing matches like ever in no time.

Anchor: Thanks Younis

Younis: A big thanks to all those suckers who wasted 3 precious days of their lives watching us… Thanks all

iSamaa – Powered by SeenReport, our first sale

This news has been in the pipeline for quite some time. We wanted to break this news earlier, but there was a lot of work to be done. Now that most (if not all) of the work is complete, I can proudly announce,

SeenReport has secured Samaa tv as its first client. SeenReport will provide its live reporting platform and social media suite to Samaa tv to build its Citizen News platform, iSamaa.

The site, iSamaa.tv is already live. Getting a client within one year of its launch (10 Jun 08), is indeed a great achievement for which the whole team is to be congratulated.

When we (Me, Sharjeel and Yaser) left our jobs and started working together, we didnt know how to make money, do marketing, make sales or run a business. However, we strongly believed that,

  1. Every huge business starts with a small scale
  2. We can use technology to create things. If we create something that solves a problem and creates value, the money will follow.
  3. We make a great team, together we can do great things. And if we do great things, we will achieve great results

Our initiative was met with critique, particularly from many ‘Experts’ on ‘Business’. These experts graciously took time out from their jobs/studies and gave us hours long lectures and highlighted how we were destined to doom. The free advice would be,

“You guys are just techies, you don’t know how to run a business”, “You wont make money…Period!”, “You’ll be on the streets on 6 months”, “Who cares about the value creation, its about the money”, “This is not Silicon Valley dear, you guys are wasting yourselves”, “Create value then money? Yeah maybe in books, but not in real life”, ”You should work for 6-8 years, then do an MBA before you even start thinking about working for yourself”

Each negative comment left us with stronger dedication. After all, why should we take advices about running business from people who have never run any business themselves. Ironically, such remarks never came from any of the founders and CEOs (both successful and failed). In fact, all the founders we met had a high degree of maturity and encouraged us to go ahead with our venture.

In the past one year, SeenReport has come a long way. From a single page web site to a full blown citizen news platform that offers live mobile reporting, online news community portals and news publishing mechanism. During this journey we created something valuable, helped common people get noticed, met great people like Mr. Shahid Malik, Rabia Garib, Jawad Farid, Jehan Ara, Dr. Umar Saif, Amir Jahangir, helped activists like Dr. Awab manage and organize information in a better way, played our part in covering the long march 08, 09 and had lots of fun while working together on something that we all loved.

But it wasn’t a walk in the park; far from it. During the past year, we’ve had 72 hours long work days, at times spent weeks in the office, slept under our desks, worked without pay for months, lived off the occasional consultancy and nearly sold our PS2 :) . But even in the extremely desperate times, we never lost faith in the team. If one faltered, another would present its shoulder and bear the weight. I can only thank Allah who blessed me with such a great team.

I would like to thank,

  • Baoo jee (aka Belal Muhammad Hashmi) whose smoke filled late night sittings showed us way when it was pitch dark
  • Hashim Ali (CEO Mantaq Systems Pvt. Ltd.) whose selfless guidance and encouragement gave me confidence to achieve anything
  • Mr. Shafiq-ur-Rehman, whose energy filled discussions kept us motivated
  • Mr. Shahid Malik and Rabia Garib, whose sincere advice helped us set our direction
  • My family, for understanding and never putting any pressure on me
  • My friends, who never lost faith in me
  • My ex-colleagues who always encouraged me to aim higher
  • My not so friends, whose constant critique and harsh remarks kept us going even when we wanted to give up

But above all, it is the grace of Allah Almighty that helped us at each step. Without His help, we wouldn’t have achieved anything. And of course, the team that made this possible.

It is fitting that the SeenReport’s first deal is with Samaa tv that has already established itself as the leader in innovative journalism and represented Pakistan in Stanford Innovation Journalism conference 09. We believe that Samaa’s initiative to empower common people to make their voices heard, is aligned with SeenReport’s vision of ‘Make news, Be heard, Bring change’. Powered by SeenReport’s state of the art platform, Samaa’s citizen news portal now has a perfect blend of mobile reporting, rich content publishing, community driven content, live news publishing, localized news and user engagement in news.

I would like to congratulate and thank the SeenReport team (Yaser Awan, Sharjeel Ahmed and Umar Saif), a team of highly capable friends and immensely talented guys whose hard work, faith and constant struggle made this dream a reality.

I am sure this is just the first good news from the series of good news to follow :)

Edit: Here is Yaser’s view on the same news 

django: How to get model class from model name

How do you get the model class object from a string containing model name?

This came up multiple times during SeenReport development. While recording views, saving votes and adding comment on an object, I had to get the model class using the model name. The scenario would be,

  • The view receives the model name and object id
  • Fetch the object from db
  • Perform action on the object

However, I couldn’t find a suitable way to get model class from the model name. The best way I could find was by using the globals function. Here is how it worked,

def my_view(request, model_name, object_id):
      model_class = globals()[model_name]
      obj = get_object_or_404(model_class, id=object_id)
      # perform required actions and return response

However, using globals requires that the models should already be imported. This would fail for a model that didn’t exist in global scope. Also I had to needlessly import models in views.

My guess was that there should be solution in the content types framework. After poking around for a while I found ContentType.model_class. This is how the above code would look like,

def my_view(request, model_name, object_id):
      model_class = ContentType.objects.get(model=model_name).model_class()
      obj = get_object_or_404(model_class, id=object_id)
      # perform required actions and return response

Younis Khan, Is he smoking pot?

Pakistan cricket team has seen its share of bad moments. From its losses to India (WC 96), Bangladesh (WC 99), Ireland (WC 07) to first round exists in WC 03 & 07. But at the end of every defeat there was at least a sense of shame if not determination. However, this time Younis Khan has come up with the excuse of the century.

After losing to England in recent T20 World Cup, with a performance that would have put my high school Cricket team to shame, Younis Khan, the hailed captain of our mighty team delivered the ultimate press conference. Rather than accepting the short comings and showing determination to improve, he told the world that its OK if Pakistan are knocked out of first round.

younis-idiot-1

Is he on drugs? Did someone dunk his head in toilet and made him lose all senses? Is the lack of Iodine affecting his brain? Did aliens abduct him and performed their notorious experiments on him?

Not a disaster? Its fun Cricket? I cant believe these words and what a huge joke it is with our country and cricket fans in Pakistan. I mean, here is a team that is treated as superstars, pampered to the height of being spoiled and raised like kings. When Pakistan plays a match, millions are glued to their television sets. People pray for them, defend them around the world, hail them, cheer every stroke, dance on every wicket taken. When Pakistan loses a match, people get heart attacks and break their televisions. They want Pakistan to win and make them proud. And our captain repays their faith by showing an utter non-seriousness towards the sport.

Yes, when Holland beat England, it was fun, but Mr. Younis was probably looking at the Holland camp who were very rightly celebrating. Mr. Younis should have tried reading some of the English papers who bashed the England team so hard that their ancestors would have felt the pain. Very rightly, the English team acknowledged their failure and bounced back in thumping manner.

May I remind you Mr. Younis that Pakistani nation and sports fans spend a huge amount of money on your grooming, fitness and travel. Every time you enter a tournament, you are representing Pakistan and carrying the hopes of the whole nation. If you do not have the desire to win and perform, please deprive us of your prestigious company. Let us see how much ‘fun’ you have when you are a nobody.

younis-idiot-2

WWF stands for World Wild Life Federation which is hardly similar to T20 cricket. I am assuming Mr. Younis is referring to WWE (World Wrestling Entertainment). He is unaware that WWF has been known as WWE for past 9 years, which pretty much explains his knowledge towards wrestling.

Imagine going to your boss and telling hims that skipping the deadline is not a disaster, the actors slacking because the movies are ‘just for fun’, game developers sleeping at work because ‘its entertainment’.

I believe that players should be accountable to someone. If they are not taking the responsibility seriously, they should be sacked and replaced with the people who are passionate and have a desire to win. Not some idiot who has fun at the expense of Pakistan Cricket fans. I wish I could write the comments all my colleagues gave about Mr. Younis, but my decent nature doesnt allow it. Its a sad sad period of Pakistan Cricket, when failure is not only acceptable, its celebrated.

No I dont want to tell you my shares in my company

 

I get a lot of irrelevant and annoying questions while talking to people, but none is more annoying than this one,

How much shares do you own in the company?

The weird thing is that it never comes from my friends, but from people who I cant befriend even in a million years. This is how it happens,

Random Guy: How is your company going?

Me: Going good by the grace of God, thanks

Some random chat about weather, sports & politics, nothing to indicate we are intimate friends

Random Guy: So, how much shares do you own in the company?

Me: (confused, trying to understand why he considers himself my best chum) hmm…well, I cant really tell you that.

Random Guy: OK I understand, but still, how much do you own?

Me: As I said, sorry, I cant tell you that

Random Guy: 50%, 40%, 30%?

Me: (getting annoyed) As I said, this in completely internal to company and I cant tell you that

Random Guy: OK, but how much do your partners own? Which one of you has the majority shares?

And this continues till I get pissed off and vow never to talk to this guy again. This question is so annoying that its almost offending. I am ethically as well as legally bound not to expose this to anyone. And certainly not to a random guy who clearly has no regard for my privacy.

Since most of the people dont seem to take hint from polite refusals, I ll spell it out for them,

No, you are not my best friend and I absolutely do not want to tell you how much shares I, or anyone of my partners owns, Period!

An advice before you seek advice

 

I meet a lot of students and budding entrepreneurs who are looking for advice ranging from projects, technology choices, academia, business and startups. The simple fact that someone chooses to listen to my opinion humbles me and I try my best to help them in best possible manner.

I was very intrigued by the post by Yaser on responsibilities of an advisor so I decided to highlight other side of the coin, the responsibilities of people seeking advice. So this post is for anyone who seeks advice from anyone whether he is an entrepreneur or not.

Why do you seek advice?

Asking for advice makes you vulnerable because what you decide next now depends on the input from someone other than yourself. It is important to know that you are vulnerable because you can then take steps to ensure that you dont make a hurried decision. Never commit to something during or immediately after the advice. The best way is to take some time, sleep over it and then make up your mind

Always ask the relevant advisor

This is one of the biggest mistake people make and not surprisingly. After all, the natural reaction of someone in trouble is to hang on to anything that is available. You should always ask the relevant person. This is difficult because you may not have a relevant person in your circle, but keep looking for the right person.

Mind the background

Every advice is loaded biased with the experience of the advisor. So when someone says “Compiler from Sir Shafiq is a terrible course” its probably because he had a bad experience with him. And when I say “If you didnt take Compiler from Sir Shafiq, you dont know Programming” its because I ve had great experience with him. An advice is not absolute and you can even get conflicting advices from the same person based on how his experience has changed.

Resist the decision

If you are seeking advice, its a good indication that you are confused. Consequently, you want to jump to the first decision that you hear. However, resist the temptation to make an easy escape into certainity. Do not take decision from others, in fact avoid the advisors who have a habit of making decisions for you.

Question the advice

This is difficult because you are already in a confused state but you should still question the advice. The process of reaching to the decision is extremely important because it identifies the issues and creates a roadmap for you.

Its your career

Every advice comes with a hidden disclaimer,

“Do not come back and blame me for if it doesnt work”

Always remembet that its YOUR career, its most valuable to you and not to someone else. Others can help you, assist you, advise you, but eventually its your life. You should make the decision yourself because the advisor will not take the responsibility of any kind. You should always have yourself to blame for and no one else.

This is also an advice

Everything above applies to this post as well :)

django: How to expire session on browser close

django employs cookies to track the user session. settings.SESSION_COOKIE_AGE defines the session expiration age in seconds. So, the user logs in once and can stay logged in for hours (even days).

But what if a user wants the session to expire as soon as the browser is closed? This is perfectly desirable for users on public/shared computers.

As always, django comes for rescue with a 5 minutes solution :) . There is a variable SESSION_EXPIRE_AT_BROWSER_CLOSE in settings.py, if set to True, django will expire session as users close the browser window.

So you have two options,

  1. Policy 1: Keep user logged in as required
  2. Policy 2: Expire the session when user closes the browser

Ideally, the user should be able to choose if he wants to remain logged in or not. Fortunately, django comes equipped to handle this issue. You can utilize session.set_expiry to determine the policy. Here is how it works,

  1. Add a ‘Remember me’ checkbox in login form
  2. If unchecked, call request.session.set_expiry(0)

And you are all good to go :) . You can call request.session.get_expire_at_browser_close() at anytime to
check which policy user has opted for

Cycorder, a free video app for iPhone

So you’ve got your hands on that sexy looking iPhone (2G/3G), you are feeling really proud of yourself, looking down on all those Nokia, Samsung, Sony Ericsson users.

Now you are showing it off to your friends, making them jealous by moving your fingers over the wide screen and enjoying the videos downloaded from youtube. When suddenly you realize,

It cannot make video!

WTH! suddenly you go from hero to zero. You quickly hide your iPhone and try to pretend from next time that you dont own one, only for your friends to bring that up and embarrass you.

I have no idea what Apple accomplished by providing a huge screen, crisp display, integrated YouTube! but not providing the video capture.

Cycorder brings video to iPhone, for free

As always, hackers came to the rescue and have now released an app Cycorder. The app is very simple, which is exactly it is supposed to do :) i.e. make video. The resolution is 384×288 at a reasonable FPS. What you need is a jailborken iPhone and simply install the Cycorder app from Cydia store or the app installer. And viola, you have video…and did I mention it was free :)

 

Images from:

http://www.smh.com.au/ftimages/2007/06/30/1182624213249.html

http://laughingsquid.com/barking-iphone/