News, ideas and randomness

Finding your nearest Diet Club

Posted: April 7th, 2011 | Author: Scott Barnham | Filed under: portfolio | No Comments »

A few months ago we developed a simple proximity search or “find your nearest” site for online marketing consultants OLCM. The site helps you find the nearest diet class from clubs like Weight Watchers and Rosemary Conley.

I’m pretty happy with the project. It was done in a short time and reasonable budget, but made to be reusable across different niches.

We used Django with some customisations to admin so that data can be uploaded from csv files. The proximity search uses a postcode-to-lat/lng database for when a postcode is entered and geocoding from Google Maps when a place name is entered.

The site is proving popular so far and we hope it will be a great success.


Using images for background text

Posted: February 7th, 2011 | Author: Scott Barnham | Filed under: web development | No Comments »

Background text: What to type in the field

It’s very common to use ‘background text’ in form fields to indicate what should be typed in there. For example, ‘name’ and ‘email’ in grey text means you should type your, um, name and email address, in to those fields.

The normal way to do it is put text in the fields, set the colour to grey using css and then remove it when the user clicks in that field. It just takes a couple of lines of JavaScript.

But what happens if you want text in a search field, or other field that you want to set the focus on when the page loads?

Background images so the field can have focus

An alternative I’ve used a few times is to have an image containing the grey text and show that image whenever there is no text in the field, regardless of whether the field has focus.

Here’s an example from London taxi booking site Tick Tock Taxi:

The “address, postcode or place of interest” text is a background image and the focus is in that field when the page loads. As soon as the user types something, the image is hidden. If they delete all text from the field, the background image comes back.

A fancier example is from hosting reviews site WhoIsHostingThis.com:

Here the text is typed in after ‘http://‘, so we actually swap between two background images – one with just ‘http://‘ and one which also has the arrow and ‘Enter the domain here‘. It shows an advantage to using images – you can put arrows and other graphics to better explain or draw attention to the field.

Here’s some code.

jQuery:

BackImage = function(field) {
    field = $(field);
    field.bind('keyup', function(e){
        field.toggleClass('empty', field.val() == '');
    });
}

new BackImage('#search_field');

MooTools:

var BackImage = new Class({
    initialize: function(field) {
        this.field = field;
        field.addEvent('keyup', this.update.bind(this));
        this.update();
    },
    update: function() {
        this.field.toggleClass('empty', this.field.get('value') == '');
    }
});

new BackImage($('search_field'));

CSS

The css just sets a background image when the field has class ‘empty’.

#search_field.empty {background:#fff url(../images/bg-search-empty.png) no-repeat 5px center;}

That’s it, a simple technique to have background text while allowing the field to have focus.


Mobile ticketing from TicketSense

Posted: February 1st, 2011 | Author: Scott Barnham | Filed under: portfolio | No Comments »

It’s always nice to see innovation in an established industry. Selling tickets for events hasn’t changed much until recently when the web and mobile phones made it cheaper and easier to sell tickets directly to customers.

TicketSense is a UK company which helps event organisers and venues sell tickets direct to customers’ mobile phones. It’s automated and pretty slick: Customers text a keyword like ‘thewho’ to a special number to buy a ticket. They can pay by credit card, PayPal, or on their phone bill. The ticket is sent to them as an SMS text message with a barcode image attached – no need to print and distribute paper tickets.

When the customer gets to the gig/event, they show the barcode on the screen of their phone and the door staff scans it with a barcode scanner.

We helped TicketSense by developing a barcode scanning app for Windows and Mac OS X which integrates with their ticketing backend. Door staff or event managers download the list of tickets sold, then scan them at the door, which checks them against the list.

We made the app simple to use with an obvious interface that’s easy to read in low-light conditions. We developed using XULRunner to make a single cross-platform application.

The guys at TicketSense knew what they wanted and were a pleasure to work with. We got some great feedback from them about the quality of our work and responsiveness.


London Taxi Quotes and Bookings

Posted: August 9th, 2010 | Author: Scott Barnham | Filed under: Django, portfolio | No Comments »

If you’re looking for a taxi in London, check out Tick Tock Taxi, the new taxi booking site recently launched by our friends at mochii.

Instant Fare Quote

Enter the address you’re at and where you want to go and the site gives you an instant quote for a mini-cab. Booking is easy, just enter your name and phone number.

Tick Tock Taxi

Behind the scenes, there’s a database of cab companies, the nearest of which is notified and will contact you within minutes. It’s a simple and painless way to find the cost and book your taxi. There’s a mobile version under development, too.

Fun Project

We did the web programming for the site using Django. It integrates with Google Maps for the address lookups (geocoding) and to find the distance by road for the fare calculation (using Google Maps directions). It uses an SMS gateway to send text messages to customers and taxi companies.

Tick Tock Taxi was conceived by mochii who also provided the design work. They called us in to do the web development side and we’re happy to be involved.

Do you have an innovative website, web-based or mobile app? Get in contact.


Dynamic Data Filtering for WhoIsHostingThis.com

Posted: July 14th, 2010 | Author: Scott Barnham | Filed under: portfolio | No Comments »

We’ve worked on the WhoIsHostingThis.com site for several years, since it was taken over by web marketing experts Quality Nonsense. It started as a tool to tell you which web hosting company is hosting any site, but has changed and expanded in scope and usefulness, adding honest reviews and special offer hosting coupons over the last couple of years.

Hosting Comparison Tool

A few months ago we helped launch the new hosting comparison tool which filters tens of thousands of data points to tell you which web hosting company is best for you. Our role was to develop the comparison engine and super-slick dynamic interface which updates the list of suitable hosts as you click features and criteria that are important to you.

Data Update Interface

Behind the scenes, the team at WhoIsHostingThis.com add web hosting plans and regularly update masses of data using an interface we developed. All changes are logged, checked and approved before going live on the site.

Tech

The WhoIsHostingThis.com site uses PHP and MySQL. Much of the work for the hosting comparison tool was client-side, using JavaScript and the MooTools library. The filter uses ajax to update the list of hosts without reloading the page making it quick and simple to compare and contrast hosts.

Job Done

WhoIsHostingThis.com is probably the largest site we regularly work on and Quality Nonsense is a great client. We’re happy with the work we’ve done and it has been well received by testers and reviewers.


Don’t delete an image file when deleting a Django model instance

Posted: March 2nd, 2010 | Author: Scott Barnham | Filed under: Django | Tags: | 1 Comment »

If you have a Django model with a FileField or ImageField, when you delete the model instance, the associated file or image is also deleted. In most cases this is desirable and keeps things tidy, but I had a situation recently where the image file should not be deleted when the model was deleted. Here’s a simple way to override the default behaviour.

Custom file storage

Django uses storage classes to determine how files are read and written. Normally, the data is just written as files to disk, but there are other possibilities such as storing on remote servers.

It’s easy to write a custom file storage class to override the behaviour of the default FileStorageSystem. In this case, we only need to change the delete method so it does not delete the file.

In custom.py

from django.core.files import storage

class NoDeleteFileStorage(storage.FileSystemStorage):
    def delete(self, name):
        pass

We can then use the custom file storage by making an instance and passing it to the ImageField.

In models.py

from custom import NoDeleteFileStorage

ndfs = NoDeleteFileStorage()

class ImageInstance(models.Model):
    image = models.ImageField(storage=ndfs, ...)

It’s as simple as that! Custom file storage has some interesting possibilities. With it you can handle how files are named or integrate with some caching or CDN.


Custom web, Django and mobile development

Posted: February 8th, 2010 | Author: Scott Barnham | Filed under: Company | Tags: , | No Comments »

We started Red Robot Studios in 2008 to develop web-based apps using great technologies like Django. Since then we’ve learned an enormous amount about what it takes to build and deploy large-scale web applications, and as we’ve developed and released our own sites and apps, we’ve increasingly been approached by people who want us to work with them to help them build great sites and services.

We’re still going to be building and releasing our own projects but have also decided to offer our development service to clients as well. We have some excellent clients already and will be accepting work from new clients.

Our aim is not just to provide a normal development service but to help our clients achieve their goals. We want to help and advise based on our experience and go the extra mile to provide really great development services to all our clients.

Our main focus is Django developmentiPhone and mobile development, but we are well experienced in many other areas including things as diverse as WordPress plugins, Facebook apps and Firefox extensions. We’d love to hear about your great idea, so get in touch!


Requiring https for certain paths in Django

Posted: February 6th, 2010 | Author: Scott Barnham | Filed under: Django | 2 Comments »

A while ago I wrote about Securing Django with SSL. Here’s a small addition.

Some paths need https

If you’re using SSL it makes sense for certain parts of the site to require a secure connection. For example, the admin section.

Previously I shared the secure_required decorator which forces requests to use https for specific views. This works ok, but if you know an entire section of the site under a given path (e.g. /admin/) should be secure, it’s hassle to have to add the decorator to each view.

You can require secure connections over https using webserver config or using Django itself.

Requiring https using Nginx

In your Nginx config file under the section for the unsecure http/port 80 server you can specify a location path and redirect all requests to it to https instead.

server {
    listen 10.10.10.10:80;
    server_name example.com;
...
    location /admin {
        # force admin to use https
        rewrite (.*) https://example.com/$1 permanent;
    }
...
}

Apache and other web servers can have a similar configuration.

If you can configure it in the web server, that’s more efficient because the request can be redirected by the server, without having to contact your Django project. However, it should be fairly rare for requests to be redirected like this so it’s not a big performance issue and sometimes it’s easier to handle things in Django.

Requiring https using Django middleware

In Django it’s easy to write custom middleware which gets called before each request reaches a view.

Here’s a small piece of middleware which checks if the request is over http to a path we want to be secure and if so redirects to the same path but over https.

from django.http import HttpResponsePermanentRedirect
from django.conf import settings

class SecureRequiredMiddleware(object):
    def __init__(self):
        self.paths = getattr(settings, 'SECURE_REQUIRED_PATHS')
        self.enabled = self.paths and getattr(settings, 'HTTPS_SUPPORT')

    def process_request(self, request):
        if self.enabled and not request.is_secure():
            for path in self.paths:
                if request.get_full_path().startswith(path):
                    request_url = request.build_absolute_uri(request.get_full_path())
                    secure_url = request_url.replace('http://', 'https://')
                    return HttpResponsePermanentRedirect(secure_url)
        return None

In settings.py

MIDDLEWARE_CLASSES = (
...
    'myproject.middleware.SecureRequiredMiddleware',
)

HTTPS_SUPPORT = True
SECURE_REQUIRED_PATHS = (
    '/admin/',
    '/accounts/',
    '/management/',
)

SECURE_REQUIRED_PATHS is a list or tuple of paths that should be secure. Any request to a path which starts with one of these will be required to use https.

HTTPS_SUPPORT is a custom setting to make it easier to use this on your dev server without SSL support. Set it to True in the settings for the live server and False in the settings for the dev server.

So there we go, an easy way to require secure https requests for certain parts of your Django site.


Find Nearby Developers on Djangogigs

Posted: June 23rd, 2009 | Author: Scott Barnham | Filed under: Djangogigs | Comments Off

Djangogigs is a very successful job board we run for web developers who use the Django framework. A few jobs and freelance gigs are added each week and there is a large directory of developers available for hire.

Finding Django Developers

As the number of developers increases, it becomes harder to find the person you are looking for. A while ago we added filtering by country, but for large countries such as the US, there are still way too many developer profiles to look through. We now have nearly 700 Django developers on the site and needed to find a better way.

The solution we chose was geocoding the location of each developer so that we can find developers who are close to a given location. Ignoring the technical stuff, it’s very easy to use. Just type in the name of your town or city and get back a list of developers who are nearby.

We’re confident this will make it much easier to find Django developers and may add other search options in future. As always, we’re happy to hear your feedback.

Follow us on Twitter

We’ve also added a Djangogigs Twitter account which you can follow to see the latest gigs as they are added.


Securing Django with SSL

Posted: February 18th, 2009 | Author: Scott Barnham | Filed under: Django | 2 Comments »

When we built the centralized authentication system for Red Robot Studios we wanted all authentication and account resources to be available solely over https.

This article covers some tips and tricks we discovered while building the app, and how you can use Django to get fine-grained control as to which resources are available securely.

Why bother with security?

We all know that data sent over http is cleartext and can potentially be read on any network between the client and server. But the risk feels pretty minimal and many sites don’t bother using SSL to encrypt sensitive traffic. For online banking and ecommerce, you’d be crazy not to use it, but for other sites, why bother?

The chances of your http requests being snooped upon by an ISP, intermediate networks or your hosting company seem minimal. But one potentially big risk is users accessing your website on an open wireless network.

For example, perhaps your user has an unsecured wireless home or office network or maybe they use wireless networks in coffee shops and airports: It’s really easy in this situation for sensitive requests to be snooped upon.

The data on your website may not be sensitive, but if you use Django’s admin or authentication frameworks, two important bits of information are passed as cleartext.

When a user logs in, their username and password is posted in cleartext. Assuming login is successful, each subsequent request includes a cookie containing the sessionid. The sessionid is just a random string, but if you know the sessionid of a user, it is trivial to hijack the session and have the same access to the website as that user does until they log out.

Encrypting login sessions

If you want to be sure user credentials and sessions cannot be compromised by eavesdroppers, you need to use SSL encryption. Install an SSL certificate on the server so that traffic is encrypted end-to-end between client and server.

You probably don’t want the whole site to be secure because it will be a lot slower and significantly increase the load on your servers. Instead, you can be selective about which parts of the site should use https instead of http. If you want user sessions to be secure, you should make sure that logging in and all parts of the site that require a logged-in user use https.

SSL

Standard SSL certificates are pretty cheap these days – under $20 per year. We go some from RapidSSLOnline. Each secure site needs its own IP address, so if you’re hosting multiple sites using virtual hosting, you’ll need to look in to getting some dedicated IPs.

There are lots of guides to installing SSL certificates and configuring web servers such as Apache, Lighttpd and Nginx, so I won’t cover that here.

Making Django sessions secure

Django uses cookies for its sessions. When a cookie is set, you can specify that it be a secure cookie, meaning it is only ever passed over https and not in http requests. We can tell Django to use secure cookies for sessions by adding a setting to settings.py

SESSION_COOKIE_SECURE = True

If you set Django to use secure cookies then try to log in over http you will get the error

Looks like your browser isn’t configured to accept cookies. Please enable cookies, reload this page, and try again.”

This happens because Django sets the cookie, but it’s a secure cookie, so when the page loads over http, Django can’t see the cookie and so assumes cookies are disabled in your browser.

Requiring https for admin

To avoid this cookie warning and make sure you only ever pass your admin credentials over https, you can configure your web server so that any http requests are redirected to https.

For example, in Nginx it would look like:

server {
    server_name example.com;
    location /admin {
        # force admin to use https
        rewrite (.*) https://example.com/$1 permanent;
    }
...
}

In Apache, something like:

<Location /admin>
    RewriteRule (.*) https://example.com/$1 [L,R=301]
    ...
</Location>

Of course, these bits of config should go in the http config, not the https config or you will cause infinite redirects!

Requiring https for certain views

If all the logged-in parts of your site are in a certain path (e.g. /accounts/ and /members/) you can configure your web server in the same way to require https for these locations.

If certain views require https (e.g. /members/bert/ is public but /members/bert/edit/ requires login), you may want to check request.is_secure() in those views. A neat way to do it is with a decorator which can also redirect any http requests to https.

from django.conf import settings
from django.http import HttpResponseRedirect

def secure_required(view_func):
    """Decorator makes sure URL is accessed over https."""
    def _wrapped_view_func(request, *args, **kwargs):
        if not request.is_secure():
            if getattr(settings, 'HTTPS_SUPPORT', True):
                request_url = request.build_absolute_uri(request.get_full_path())
                secure_url = request_url.replace('http://', 'https://')
                return HttpResponseRedirect(secure_url)
        return view_func(request, *args, **kwargs)
    return _wrapped_view_func

Then on your view:

@secure_required
@login_required
def edit_member(request, slug):
    ...

Moving between http and https pages

It’s normal to use full path URLs like /accounts/login/ and /blog/. Bear in mind that if you are accessing the site over https and follow one of these links, you will also access them over https. If you want to be explicit, you need to specify the protocol and domain in the links, e.g. https://example.com/accounts/login/ and http://example.co/blog/ .

For $20 and a bit of config, you can secure logged-in sessions on your site and protect yourself and your users from being compromised by eavesdroppers. There are still plenty of sites where this is overkill, but you can see now how easy it is to secure your Django site with SSL.