Mobile Template Mixin for Django Class Based Views

I am currently working on a web app and the application would have mobile and desktop versions respectively. At first, I considered the all so beautiful responsive approach but I figured what I wanted the mobile user to see should be straight to the point as opposed to giving the desktop users some more content and then hiding or realigning the view. I just thought instead of making CSS 3 Queries to determine what platform is making the HTTP request, and then respond appropriately, I decided to create one application that would display different but all so familiar views depending on where the user is making the request.

Now I know many school of thought have argued about whether building one application and using queries is the best or whether building different application for each platform is the best. I don’t think any side wins this argument. It often depends on what type of application you are building. But I choose to build one application but different display endpoint (in this case templates to render the HTML). However, that’s not the gist of this article. I think I’m beginning to bore myself with all this story.

I wanted to write a mixin that would spew the right template depending on where the request is coming from. I google’d different tutorials and articles but nobody was giving me exactly what I needed. So I went to look at the Django source code itself. The Django documentation also helped. To cut the long story short, here is my mixin below.

appname/mixin.py

class MobileTemplateMixin(object):
"""
Use this mixin if you have a different templates for your mobile and desktop applications.
"""
template_source = None
template_name = None

def get_template_names(self, *args, **kwargs):
if self.request.is_mobile:
self.template_source = "mobile/"
else:
self.template_source = "desktop/"
self.template_name = self.template_source + self.template_name
return [self.template_name]

But pls note that you will need a middleware to enable the is_mobile feature on the request. You could check this rather succinct middleware I stumbled on http://sullerton.com/2011/03/django-mobile-browser-detection-middleware/ You will need to add this middleware to the MIDDLEWARE_CLASSES in settings.py. It would look something like this

settings.py

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#add middleware to support mobile detection
'myapp.middleware.RequestDetectionMiddleware',
)

Its important that this middleware comes after the django.contrib.sessions.middleware.SessionMiddleware.

However, I stumbled upon a road block and hopefully someone out there could help clean up this piece of code or give me a better way of implementing this. You will have to created a template directory like so;

templates
desktop
appname
index.html
mobile
appname
index.html

I don’t like that structure because it looks very redundant. So what I would want to do is determine what app a template is been requested for and parse that into the mixin. However, this is what I have so far and it work.

so to use this, just add the mixin to your class view

appname/views.py

class MyView(MobileTemplateMixin, TemplateView):

template_name='appname/index.html'

This would resolve to the template name; desktop/appname/index.html for desktop request and mobile/appname/index.html for mobile device request.

I hope someone finds this useful. I’m sorry if the code is not properly indented. I’m not sure how to go about it but I’m sure it would be easy to figure out.

Looking forward to 2013

If we take account of 2012, for some of us, it was a wonderful year while for others, it was just one of those years we wished passed on quickly. For some, it had been victories and great accomplishment all the way. For others, it has been a sore story of failures and defeats. Be that as it may, there is a coming year to look forward to.

No matter what 2012 was like, 2013 could be better. You just have to believe and work towards it. Now, I’m not going to try to state some of the things you probably have tried in 2012 and had not succeeded for those who have had a not so pleasant year. And this is not going to be one of those long epistle-like article. If you have experienced more failures than successes in 2012, don’t despair. Sometimes, failure is not because we are not trying hard. It might just be because we are not trying right. Maybe you have had projects you started and did not complete or you bid for a project with a competitor and they won it over you, you should take this as a lesson and learn from it. Be honest and ask yourself these questions and answer them sincerely.

Do you deserve what you got from your effort? Why? Did you exhaust every options opened to you? Did you listen when people gave you advice? Did you seek for better ways of doing what you are doing currently? Were you opinionated about your work? Did you hang out often with people who do the kind of things you do? If you wanted to employ someone on a new project, would you consider someone like you to meet the budget and deadlines? Etc.

I could go on and on but I believe these few questions would spark up some deep thoughts. Whether it was a good year for you or not, there would have been somethings you could have done better. So don’t sit in the attic and cower out in fear of the coming year. Be optimistic. Be proactive. Learn from the mistakes you made and move on quickly. The world out there needs all the skills you have to offer. There would be more opportunities in 2013. Look forward to it and prepare for it adequately.

Happy New Year in advance!

Embrace Change

Well, this article is not in any way “techy” or technology related. It cuts across every sphere of human endeavor. So don’t expect to read something that is technology-centric. It is an article meant to share my experience in recent times.

Now, when we think of it, how do you define change? The truth is, no definition would accurately define change because it means different things to different people. So I will keep it simple and please note that this is my opinion. Change in simple terms is a deviation from the norm. A different turn from what used to be the usual or accepted status of things. For example, there was a time when magazines where the best platform to read your favorite articles of interest. But when the internet came, things changed. The accepted status-quo that when you wanted to read the latest trend on fashion, you just took a walk to the nearest tabloid stand and pick a copy of the latest Fashion Sense or some other magazines of its kind, took a different turn. Now people could at the comfort of their space, with an iPad or any smart device connected to the Internet gain access to the same information. This was a change and whether the publishers of these magazines liked it or not, that was here to stay. Their loyal subscribers have shifted their attention else where.I am certain, the publisher/owners of these magazines might have thought that things would always remain the same. Things never always remain the same.

The result or consequence of change depending on how you look at it, could spin either way; favorably or adversely. Change for the magazines’ publishers which in this case, was the advent of the internet, would have had adverse effect on the sales of these magazines which effectively affects the expected turnover. However, on the flip side, the change for the subscribers of these magazines, was a great and welcome development.

I think I should at this point state that this was not in anyway a shot at the magazine publishers. It is just coincidental that at the time of writing this blog, that is the example that came to mind (I love to read magazines). That’s it. I just needed to clear the air.

So back to where we left off; I use Google Reader to read a lot of things on the Internet as I often subscribe to feeds and I have come to know a lot of things that before now would have taken me loads of library time, “googling”, and hangouts. There even things things now that I have stumbled on and has amazed me. I can’t divulge all of that on this piece but my motivation is the fact that I have so much information at my finger tips. I have section for my sports information, I have sections for new gadgets, I have a section of web development trends, i have a section for latest cars etc. And at one sitting I can peruse a whole lot of information without having to do my very familiar Google search to check trends.

The question you might be asking now is, how does that affect anything? It does. I used to be a lazy reader before and that was a minus for me. I stumbled on a blog and the writer was stressing on why you need to at least read something everyday. He stated on how things are evolving everyday. If you do not keep up, you will realize that what you new yesterday would be old by 6:00pm today. He said everybody has interests in different things. So make it a duty of indulge your interests. If you love music, read up on your favorite artiste. If you love cars, there are millions of feeds on cars out there, subscribe to one. If you are a lawyer, read up on the trends of your profession. Whatever it is you do, keep up and embrace change. Today, one of the first things I do when I get to my desk is check my Google Reader. I cannot tell you how much effort it has saved me. You will be amazed that what you thought difficult to accomplish, someone has accomplished it and is making the steps to success available. When you thought you had the answer to a problem, someone out there has a better answer and everybody is listening to him. Maybe the answer you have is old. Embrace change.

Don’t sit on your oars and assume you have it locked down, keep up with trend. Make it a point of duty to yourself to indulge your interests.  Realize that what you know yesterday is fast changing to something else today and embrace change. Don’t see change as something hurtful that must be done; see it as something helpful that can be done. Be flexible. Nobody says change always comes with the good. But if you live with a mindset that when change comes, you would be ready, you will never be caught napping. Years ago it was the tabloid. Then came the television. Now we live and almost breathe in the Internet era.  Years ago it was punch cards. Then we had the cassettes. Then came the diskettes. Then the flash drives and the likes. Who knows what tomorrow holds? Whatever your profession or skill set, change will come. Look forward to it. As a matter of fact, move in the direction it is coming. Embrace it.

 

Responsive Design

If you have being following trends in recent times, you would have noticed that web application design and development has taken a turn for the best. With the push of mobile development taking the front seat, design and development of web applications will never be the same again. This is true because there are more users of mobile devices than there are of the traditional desktops (thanks to Apple, Samsung, Blackberry, Motorola, Sony Ericsson etc.). So the case today is, if you want to reach more people, you have to build applications that would scale across different platforms.

Now you may wonder, how could this be done effectively and painlessly without having to build different versions of the same web application for example for all available devices? The answer is, Responsive Web Design. If you have not heard about this, then you must be living under a rock somewhere in Nevrasla (fictitious). Its like the next buzz word in the web development and design world (I have a feeling it has been around for a while but it seems it just caught some fire, when iPhone and iPads began to cause a stare!). Responsive design has joined its buzz word contemporaries in the software development community–interaction design, reflective design, intuitive design etc. It is referred to as Adaptive design by some folks.

In my own words,

Responsive design is the ability for a system to be flexible enough to adjust itself to suit the behavior of actors and the space it occupies within the system, without sacrificing important information.

I hope that made sense. Okay, if it didn’t, then here is another definition that is more specific to the web design and development plethora. Not by me this time.

Responsive Web design is the approach that suggests that design and development should respond to the user’s behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries. As the user switches from their laptop to iPad, the website should automatically switch to accommodate for resolution, image size and scripting abilities. In other words, the website should have the technology to automatically respond to the user’s preferences. This would eliminate the need for a different design and development phase for each new gadget on the market. Coutersy of Kayla Knight

Well, that just about sums it up. I would not say anymore, why not read up the article by Kayla herself here. Let me know what you think about this interesting development in our evolving world of web design and development.

Steve Jobs and his legacy

It seems everyone has written something about Steve Jobs that is very outstanding and I must say, the man deserves all the accolades. However, it beats me to note that people seem to get this super recognition status after they die. I suspect it has something to do with what you did when they were alive.
All of a sudden, Steve’s witty sayings have sprung out all over the internet like Aristotle. Or maybe it I wasn’t looking in the right direction. Because, you don’t have search hard this time to find Steve’s quotes. They are everywhere. He spoke outstanding words that should make us rethink the way we approach everything. And when I say everything, I mean everything!

I have read so many articles on Steve Jobs lately, I can almost say I know the man personally. But its really interesting though, that in his short 56 years, he left a legacy that changed our lives and world forever. The way we look at design, the way we look at technology, the way we look at style, the way we look at products, the way we give our services, the way we derive satisfaction, the things we should expect, the way we look at ourselves etc. He redefined what we commonly called user experience. He made us see the possibilities that we only longed for but seemed no one was giving it to us. He brought satisfaction to the bare. Whenever you picked up any Apple product, you can almost bet you have bought a perfect product. You try to look for flaws but its hard to find any. There might be but its not something you can’t live without. Thats the Apple trademark. Excellence.
Steve took Apple from bankruptcy to become the most valuable company in the world, beating ExxonMobil in its wake. This is a testimony to the incredible effort of Steve Jobs and the Apple family. He made us to understand how important it is to meet a need that people silently craved for. Something they will pay anything for but no one was providing it.

My First Experience

I remember my days in the University, everytime I picked up a text and I came across sections that spoke about how to do things on Macintosh Computers, most times, I would skip it. I wondered whether people used the Macintosh at all. Well maybe in the US or other parts of the world but here in my country Nigeria, I doubted that. People had not even appreciated using the PC except for Typing Documents and the likes. At the time, I was doing just fine with my PC and that was that.

When I got my first job, I was employed as a programmer and that was my first date with the Apple iMac. ‘My God! what was this?’ I looked at this sleek looking piece of Monitor sitting on the shiny green glass table. I became a little skeptical at first. After looking at it for sometime, it looked like a cute dump terminal. There was no CPU sitting anywhere around. So I wondered, does this make any sense because this Terminal looks sleek? A cute dump terminal is nothing but dump, period. Dump terminals my foot! But I saw my boss work up to the “Monitor”, switched it on and the thing just started up like a regular PC. Pretty sweet start up screen with all this matte looking icons sitting at the bottom of the screen. I was fascinated by this “Monitor” to say the least. He (my boss) then asked someone to pull another one from its pack and they laid it on the table. He switched that on as well and viola, this thing just came to life. The screen gave me goose pimples. It was so amazing. I know I might sound a little old-fashioned but that was three years ago. After that first encounter, the rest is history…

Today, I have a MacBook Pro and I tell you, it is one of the most valuable assets in my possession. Not because of its price, but because of its worth. I have never worried about virus attack for its three years as my baby. Now that’s one edge over my now-museum-looking PC (I will keep the make of this PC anonymous not to course any issue) that I have had to use almost half of its hard drive space for Antivirus. This baby (my MacBook Pro) just never goes down. The ease of use, the ruggedness and the sheer total user experience is something else. Quality in design and attention to detail has become a signatory we associate we Apple computers and other Apple devices today. Thanks to Steve Jobs.

Steve was/is a genius

Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don’t settle.

Indeed, Steve found what he loved and settled. With the advent of the Apple iPad, the world has not remained the same again. Most times when a new product like the Tablets is presented to consumers, there will be some difficulties of use, changes that needs to be made and all that. When the iPad came, it just sat on top on the everyone’s purchase list. It became the next thing not just because it is natural for humans to crave for something new but the quality of what this new invention met. Don’t forget, the iPhones has raised the bar on smartphones already.

I don’t intend to write a whole lengthy article on my respect for Steve Jobs, his legacy and the Apply Family but I have to say this, Steve taught us how to raise the bar whether as consumers or as producers. The i prefix on Apple products was originally meant to denote Internet, but I must say, Steve made it sound like Ingenious, Incredible, Invincible to me. The iPhones, the iPads, the iMacs, the MacBooks Pros, the MacBook Air and all other products we have come to love would always be a benchmark for devices of its like for a very long time, until someone beats this legacy which I doubt. Rather, people would build on it.

With much love to Steve Jobs’ family and the entire Apple family, I celebrate the life of a man we have all come to love and are grateful he left us a legacy that the next generation would be proud of. We would never build products without user experience and satisfaction as number one factor again. We would never stop or settle until we get the best of the best. We would never give up until we produce inventions that defies the norm. Never again.

Thanks Steve. RIP.

If you are interested, you may want to read up the last two articles I read; Steve Jobs, a designer at heart and The Foolish Road of Steve Jobs and how it can work for you.

Django, the best Python web-framework

I got started with Django about 5 months ago and its been a relief. The whole framework is built with ease of use in mind. I mean you can get a working web application, from authentication to authorization, from the administrative console to a full web application in one short and quick swoop. Its amazing!
The caveat though is it being a Python Web framework i.e you must be a Python developer to use Django. For me, coming from a little bit of Java, then Flex, and PHP development, learning Python took me two months when I also started to use Django. I can’t call myself a Python Guru yet, but with Django I’m learning very fast. If you are a software developer and you want to wet your appetite, give Python and Django a try, I can bet, you would not be disappointed.

They usually say not everything that glitters is gold, but I would dare say that everything Python and Django is gold. Yeah! I have not lost my love for Flex though. So for those of you who are saying, what happened to my love for flex? I’m still a Flex developer even though I have not opened my Flex builder in a while. I hope when I do, I do not have to run off my desk because I have spiders, roaches and ants running all over my Flex Builder :)

But at the moment I am firing on all cylinder with Django and I don’t see an end of the road with this framework yet. Phew!

Before I bore you, let me just give you the path to find peace of mind as a web developer as I have found. Why not see it for yourself; http://docs.djangoproject.com/en/1.3/

I have been able to improve on some Django utilities I came up with in the process of my web development. I would be posting them as soon as I can. Still have to clean up loads of stuff.

Cheers guys,

Mime Apple’s Mac OS X shutdown dialog

I needed to notify the user whenever there was an update and he need to take an action either allow the system run its course and restart itself using a timer and user activity. I have always loved the shut dialog for Apple’s Mac . So I came up with this Mac OS X shut down style dialog window. I just did a rush job but i think it suffices for now. Please note I did not style or skin it for time constraints.  I would try and make it look a little more eye-candy when time allows me. In the mean time, I’d like you to use this and send me updates if you make any. Sorry I have tried to use the WordPress HTML processor so the blog looks more readable but I guess I did not succeed as it is. If you have a good hang of it, please feel free to send me a comment on how to do the better. I guess its an issue with all the open close tags. Anyway, the code’s below. Copy from the <?xml version=”1.0″ encoding=”utf-8″?> true to the </mx:TitleWindow> as the RestartDialog.mxml file and paste it in your flex actionscript editor as a component. Then the rest of the code should be easy to understand.

Code after the jump

RestartDialog.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:TitleWindow xmlns=”com.orangepoint.widgets.*”
xmlns:mx=”http://www.adobe.com/2006/mxml&#8221;
width=”450″ height=”150″
creationComplete=”init()”
showCloseButton=”false”/>;

<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;

/**
* Countdown Timer
*/
private var countdownTimer:Timer;

/**
* Countdown Number
*/
[Bindable]
private var countdownNumber:Number = 60;

/**
* Initialise and start the timer with a delay of 1millisecond that runs 60
* times equivalent to the 60seconds a minute countdown
*/
private function init():void
{
countdownTimer = new Timer(1000, 60);
countdownTimer.addEventListener(TimerEvent.TIMER, onTimer);
countdownTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
countdownTimer.start();
}

/**
* Close the window/dialog handler
*/
private function closeWindow():void
{
PopUpManager.removePopUp(this);
}

private function restart():void
{
// code to restart the application
}

/**
* Stops the count down and closes the dialog
*/
private function cancel():void
{
countdownTimer.stop();
closeWindow();
}

/**
* Reduces the countdown by 1 as the timer ‘ticks’
*/
private function onTimer(e:TimerEvent):void
{
countdownNumber--;
}

/**
* When timer comepletes, the dialog is removed from the screen
*/
private function onComplete(e:TimerEvent):void
{
closeWindow();
}

]]>
</mx:Script>
<mx:Label id=”messageTitle”
text=”Are you sure you want to restart the Application now?” fontStyle=”normal”
fontWeight=”bold”
fontSize=”14″
fontFamily=”Tahoma”/>
<mx:Label id=”message”
text=”If you do nothing, the system will shut down automatcally in {countdownNumber} seconds”/>
<mx:ControlBar width=”100%” height=”100%”>
<mx:Button label=”Restart” click=”restart()”/>
<mx:Button label=”Cancel” click=”cancel()”/>
</mx:ControlBar>
</mx:TitleWindow>

****************************

NOTE: You now include this in your application likecode below say on an event trigger (button click for example)

private function showRestartDialog(event:MouseEvent):void
{
var restart:RestartDialog = PopUpManager.createPopUp(this, RestartDialog, true) as RestartDialog;
restart.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow);
PopUpManager.centerPopUp(restart);

}

/** removes the dialog whenever the user click outside the dialog.
* You can take this away if you do not need it by commenting out the
"restart.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, closePopUpWindow);" line in the showRestartDialog() method above */

private function closePopUpWindow(evt:Event):void
{
PopUpManager.removePopUp(restart);
}

****************************

Feel free to let me know your take on this.