Category Archives: Programming

Django multi select multiple choice model field

To me, it doesn’t really make sense to store static data in a database – especially if there are only 5 or 6 errr datum you are wanting to store. Django allows you to use a Charfield with choices, i.e.

WIND = 'W'
    (WIND, 'Wind turbine'),
    (SOLAR, 'Solar panels')
energy_type = models.CharField(max_length=1, choices=ENERGY_TYPE_CHOICES, default=WIND)

But unfortunately you can’t select multiple choices, so in this case it wouldn’t be possible to associate both wind & solar with one of my models. It is suggested that developers store this info in a separate table and associate the choices with models using a manytomanyfield. Perhaps this makes sense if you want to associate the field options with multiple models, but it really seems overkill if you just want to have multiple choices for a single model.

Strangely there don’t seem to be many other people who have felt this to be too much (I mean, going by google anyway). As I have frequently found with Django, a few people have discussed it on stackoverflow and there are a million ways of doing the same thing with no clear indiciation as to which is most widely used and most sensible. Well, there are 3 different modules/alternatives:

  • Multiselectfield:
  • Multiple_select_field:
  • Select_multiple_field:

This is ridiculous. Django’s “do-it-yourself” attitude is refreshing after coming from PHP and Drupal, but why isn’t something this ubiquitous integrated into Django itself?  This is something many projects are going to want. Or do I have it wrong and is it better to have a separate db table for like 2 or 3 fields?

Django error: TemplateResponseMixin requires either a definition of ‘template_name’ or an implementation of ‘get_template_names()’

This is such a bizarre error message and I have spent hours trying to figure out what on earth I’ve been doing wrong. This is my situation: I have several models for which I am creating generic views for (ListView, DetailView, CreateView, UpdateView, DeleteView). These mostly contain postgis geographical data that I am storing as polygonfields and so on. To display these nicely in my forms I want to use the django-leaflet LeafletWidget. To do THIS I have to create a modelform. So for example my files look like:

class Project(models.Model):
    current_name = models.CharField(max_length=50)
    location = models.PolygonField()
    objects = models.GeoManager()

class ProjectCreate(CreateView):
    model = models.Project
    template_name_suffix = '_create_form'
    form_class = forms.ProjectCreateForm

class ProjectCreateForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ('current_name', 'location')
        widgets = {'location': LeafletWidget()}

urlpatterns = [
    url(r'^project/create$', views.ProjectCreate.as_view(), name='project_create'),

now, if you leave out the model = x bit in the createview (which i think is perfectly reasonable as you have to specify in the modelform in the what model you want to use, then you get this error:

TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'

Absolutely infuriating. I can’t believe how many hours it took for me to track this down. All because I left it yesterday and didn’t put the model = x bit back into the code when I removed it to see what happened. I also can’t believe I actually forgot about it though – senility is clearly on the horizon.

It is actually in the docs though – scroll down to the first note inset. Lesson learned: always read the docs rather than googling for stackoverflow answers!

WordPress, you suck for websites with lots of pages and no posts

My recent experiences with wordpress have made me realise that it really is a terrible solution for a website with a lot of pages (say more than 30) and no posts. It’s great at blogging though. But say you have lots of pages, you’re gonna want a menu to show those pages right? And you’re probably going to want 2 menus, one for the ‘about/contact/partners/faq’ to-do-with-the-company content, and one for the primary content. If your primary content custom menu is likely to be long (as it is in my case, at around 130 pages+), then the default menu system is cumbersome and dragging things around between levels is a complete nightmare.

And there is no solution. You can display page hierarchies instead, but this sucks because it’s useful to think about your site in terms of the menu structure, and to do half of your menus using custom menus and half of your menus using page hierarchy is shit. It’s also impossible to get your menus to automatically sync with your page hierarchy. I miss drupal. Here’s hoping this post annoys someone enough for them to post and tell me an easy way of doing what I want (just a simple menu which is easy to manage!).

Django 1.7 and Python 3.4 how to add a label class to your ModelForm using crispy forms

There’s a bug that’s described here:

which can be “fixed” by changing crispy_forms/templates/bootstrap/field.html on line 8 from:

<label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}">


<label for="{{ field.id_for_label }}" class="control-label {% if field.field.required %}requiredField{% endif %}{% if label_class %} {{ label_class }}{% endif %}">

I have no idea how to get field classes working, frankly. But it is possible to get a fieldclass using django by passing it in through a widget thank goodness. Like so:

class BookForm(forms.ModelForm):
class Meta:
model = Book
exclude = ('unecessary_field')
widgets = {
'published': forms.TextInput(attrs = {'class': 'col-lg-8-or-whatever'}),

Took me ages to work this out. I hope it helps someone.

Fixed navigation (scrolling to content headings)

I used as a foundation for a fixed navigation/scrolling type page, and modified it so it was a bit nicer and more adaptable, like this:

$(document).ready(function() {
	// Parameters
	var navOffset 	= 15,
		scrollSpeed = 500;
		animationSpeed = 100;
		cssClass = 'scrollNavOn';
		minTop = $('#content').offset().top,
		maxTop = $('#content').height() + minTop - $('#navigation').height();	
	// Place navigation
	var currentScroll = $(window).scrollTop();
	$('#navigation').css({'top' : minTop});
	// Align navigation after loading while scrolling through the content
	if( currentScroll > minTop && currentScroll < maxTop ) 
		$('#navigation').css({'top' : navOffset + 'px'});	
	// Adjust navigation top to content top and end of content
	if( currentScroll <= minTop ) 
		$('#navigation').css({'top' : minTop - currentScroll});
	if( currentScroll >= maxTop ) 
		$('#navigation').css({'top' : maxTop - currentScroll});
	// Get section positions to use later
	var sections = [];
	$('.scroller-sections').each(function() {
		sections.push([$(this).attr('id'), Math.floor($(this).offset().top)]);
		var currentSection = $(this);		
	// Set the click functionality for the nav
	$("#scroller-navigation li:not(.notsection)").each(function(index) {
		$(this).click(function (event) {
			var targetOffset = sections[index][1] - navOffset;
			$('html,body').animate({scrollTop:targetOffset}, scrollSpeed);

	// On scroll highlight the correct nav item
	newNavIndex = 0;
	$(window).scroll(function() {
		// Current scroll
		var winScroll = $(window).scrollTop();
		// Align navigation to window scroll while scrolling through content
		if( winScroll > minTop && winScroll < maxTop )
			$('#scroller-navigation').css({'top' : navOffset + 'px'});
		// Adjust navigation top to content top and end
		if( winScroll <= minTop ) 
			$('#scroller-navigation').css({'top' : minTop - winScroll});
		if( winScroll >= maxTop ) 
			$('#scroller-navigation').css({'top' : maxTop - winScroll});
		// Iterate through the different sections and work out which nav element to highlight
		for(var i = 0; i < sections.length; i++) {
			// Work out which section we are on - get the top of our current section and the top of the next section
			var lowerLimit = sections[i][1] - navOffset
			var upperLimit = $(document).height(); // If we are on the last section  set upperlimit to be document height
			if(i < sections.length - 1) 
				upperLimit = sections[i + 1][1];

			// Run through each section height and see whether it's between the upper and lower limits, and also whether we've scrolled down to the end of the document
			if(	((winScroll + navOffset) < upperLimit && (winScroll + navOffset) > lowerLimit) || 
				(i == sections.length - 1 && (winScroll + $(window).height() == $(document).height()))	) {
				// $('#scroller-navigation li:nth-child(' + (i + 1) + ')').css({'font-weight' : 'bold'});

				$('#scroller-navigation li:nth-child(' + (i + 1) + ')').addClass(cssClass, animationSpeed);
				$("#scroller-navigation li:not(.notsection)").each(function(index) {
					if(i != index)
						$(this).removeClass(cssClass, animationSpeed/2);

With HTML like this:

  <head> Add your CSS and JS here </head> 
    <div id="wrapper"> 
      <div id="sidebar"> 
        <ul id="scroller-navigation"> 
          <li>List your nav items here</li> 
      <div id="content"> 
        <div class="scroller-sections" id="uniqueid"> 

What someone really needs to do now is automatically build the <li>s based on how many h2s (or whatever, that should be passed in as a parameter I guess) there are in the text and set the nav up automatically.

Python script for Vortex

Vortex is used on the Conservation Biology MSc course at UCT to simulate the extinction process of a species stochastically. Its user interface in managing/renaming different scenarios isn’t great, and I was a bit lazy and ended up with a single vortex project file containing a huge number of scenarios that were redundant for my project. I certainly wasn’t going to create them all again from scratch, so I manually removed the chunks in my .vpj pertaining to the simulations I no longer wanted, and wrote a quick script which would fix all of the numbering and references throughout the .vpj program using Python and regex. I hope this will help someone else:

import re
btm = open('C:/yourpathto/vortexproject.vpj', 'r')
i = 0
outputdata = []

# Iterate through all of the scenario notes, keeping track of what number we are on and changing numbers as necessary
for line in btm:
 match = re.match('^\[(\d\d?\d?) Scenario Notes\]$', line)
 if match:
   i = i + 1
 match ='^\[\d\d?\d?\d? ', line)
 if match:
   line = re.sub('^\[\d\d?\d?\d? ','[' + str(i) + ' ', line)

# Create a new file to output the data
outputfile = open('C:/replacementvortexproject.vpj', 'w')
# Loop through each line in outputdata and add it to the new file
for line in outputdata:
# Close the file and print to screen to know the program has ended
print 'Finished'

Find a city in wunderground when there is more than one entry

Wunderground’s API website seem to cover every single possible thing you might want to do with their service, apart from, inexplicably, actually having a list of cities and corresponding codes for you to look at in order to get the weather as accurately as possible for outlying regions (in other words, to work out what the nearest city to the place you want is that they have data on).

What you have to do is go to their main website and search for your country, it’ll give you a list of names of cities. You can use these and just add %20 instead of spaces, etc, and shove it into the code example they give you, such as :

$json_string = file_get_contents("");
$parsed_json = json_decode($json_string);

But you’ll run into problems when there is more than one entry for the city you’re searching for, for example Pietermaritzberg or Nelspruit in South Africa both (oddly) have two entries – see

As far as I can see there’s nothing mentioned on their API documentation about this. It’d be fine if the json you got given back contained forecasts for both of the locations, but sadly it doesn’t. So what you have to do is cunningly look at the main website’s code, check various links to see if you can work out a possible way to query stuff, google fruitlessly, try random combinations and then (!!) take the zmw code for the city you want out of the array of responses you get, and use it like this:

$json_string = file_get_contents("");
 $parsed_json = json_decode($json_string);

In general their new website, service and api website seem very nice and organised so it’s entirely possible this information is somewhere and I was just blindly not seeing it, but I did look quite a bit and sometimes the most simple obvious things just get overlooked.

Drupal 6 Fatal error maximum execution time of x seconds exceeded

For users of date repeat api note that if you are using a calendar view and you enter a recurring date with a lot of exceptions you are going to get some really slow SQL queries and possibly some errors/max execution time exceeded errors. I found that after a while, probably as soon as views caching started kicking in, my website was pretty much unusable. So! On the offchance you have come to this post because your website is crashing, and you happen to be using date repeat + views calendar, it could be because you’ve recently published something which adds a lot of exceptions to your date repeat rule!

Python on windows 7 with Vim

  1. Download and install Vim
  2. Download this Vim script and put it in your <vim>/plugin
  3. Download python syntax highlighting for Vim and put it in <vim>/syntax (you could also look at
  4. Download and install python 3.2 from here
  5. Under control panel > system click Edit environment variables and environment variables, and either edit the system path variable or add a new path variable for your user. Variable name is ‘Path’, and put in your Vim path and your python path separated by a semicolon, like this : “C:\Python32;C:\Program Files (x86)\Vim\vim73”
  6. Edit runscript.vim (downloaded in 2) and open it in notepad to edit line 40 to “let s:PathToExecutable = ‘python'” and line 44 to let s:mainfile = bufname(‘%’). I’m not sure why the last one is needed but it seems to be!
  7. Run cmd and type ‘vim’. Go into insert mode by pressing i, type ‘print(‘helloworld’)’, press esc and save the file by typing ‘:w’.
  8. Hit F9 to bring up the output buffer and F12 to run your program!

Fighting with Vim

So, the whole point of Vim is that it’s supposed to be easy  and require as few keystrokes as possible to make stuff happen, right? Well, isn’t it odd that simply saving your work requires double the number of keystrokes that it does in notepad++ or whatever text editor? The nervous tic, the repetitive twitch of the fingers to ctrl+s every few minutes whenever you stop to look over what you’ve typed is universal. So shift + ; and then w and then enter, vs ctrl+s? What’s with that! Weiiiiiiird.

Anyway, here’s a tutorial on how to do a quick key map for ctrl+s