phpFlickr 3.1 cache unserialize error

I came across a problem today with phpFlickr 3.1 and the way it handles its database caching. I believe it has to do with commas in the serialized data that is being inserted into the cache table. After grabbing the cache result php gave me this error in the phpFlickr library:

Notice: unserialize(): Error at offset ... phpFlickr.php

To fix this error you need to base64 encode and decode the data going into the database.

in phpFlickr modify line 144 to decode the response:

return base64_decode($result['response']);

line 177 on cache row update:

$sql = "UPDATE " . $this->cache_table . " SET response = '" . str_replace("'", "''", base64_encode($response)) . "', expiration = '" . strftime("%Y-%m-%d %H:%M:%S") . "' WHERE request = '" . $reqhash . "'";

line 180 on cache row insert:

$sql = "INSERT INTO " . $this->cache_table . " (request, response, expiration) VALUES ('$reqhash', '" . str_replace("'", "''", base64_encode($response)) . "', '" . strftime("%Y-%m-%d %H:%M:%S") . "')";

Thanks to David Walsh for his php serialize tips:
http://davidwalsh.name/php-serialize-unserialize-issues

Django AuthenticationForm and non field errors

Here’s a quick tip for the built in Django AuthenticationForm in django.contrib.auth.forms: use the non_field_errors method when trying to display the incorrect user/pass error. The error is raised in the general clean method and is not bound to any field, so using form.errors doesn’t give you the error message itself.

{{ form.non_field_errors }}

Django forms: Adding a blank option to a required choice field

Recently I came across a problem where I had a django form choicefield that needed to be required, but also needed a blank choice in case the user didn’t see the field and incorrectly submitted the first value. I saw a stack overflow post recommending to make a clean method to check that the first choice isn’t selected. That post is here:

http://stackoverflow.com/questions/5289491/blank-option-in-required-choicefield

… but a better way to do this is to simply leave the value of the blank choice as an empty string, which will invalidate the form without any extra clean method, like below:


CHOICES_WITH_BLANK = (
    ('', '--------'),
    ('1', 'choice one'),
    ('2', 'choice two'),
)

class ChoiceForm(forms.Form):
     choice_field = forms.ChoiceField(choices=CHOICES_WITH_BLANK)