Django: Queryset object has no attribute ‘_prefetch_related_lookups’

After migrating an app from Django 1.3 to 1.4 and testing that all worked fine locally, I ran into this message while updating the server:

Queryset object has no attribute ‘_prefetch_related_lookups’

The problem is the Sessions, I had to delete them all for it to work. Addtionally I changed the settings SECRET_KEY so all sessions don’t validate.

This is the related Django ticket

Downloading Coding.fm sounds

I hate doing this, it just feels wrong, but I’m going to share how to do this, it turns out it was pretty simple.

Today I read about coding.fm and how it plays the sound of other people coding, I gave it a try and I loved it. I had a browser tab open all day in order to be able to enjoy this while I worked.

But I hated that I had to have a browser tab open just to listen to this sound so I went ahead and downloaded the sound.

Looking at the source of the page you will see that the player widget code works over an Iframe:

var widgetLoaded = false,
widgetIframe = document.getElementById('sc-widget'),
widget       = SC.Widget(widgetIframe),

The Iframe’s #sc-widget points to: http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F56428729&auto_play=true

Pasting that on your browser shows you SoundCloud player with the track on it. There you can click on the Crossrider’s profile and see all the tracks. So I just Googled how to download Soundcloud tracks and ran into SoundCloud Downloader.

Once you have the mp3 file, just play it with this command to play infinitely.

$ mplayer -loop 0 hacking.mp3

It just needs some crossfading to avoid the whitespace when looping through the track.

Thanks a lot to the guys from CrossRider and recording these sounds. Make sure to follow them on Twitter

Picture of crayolas

Crayola colors in JSON format

Picture of crayolas I ran into the Wikpedia page for Crayola offical colors.

The list consists of 133 colors, with names and HEX values, so with a little help of Python, it was easy to extract them into a JSON file that we can use:

[
    {
        "hex": "#EFDECD", 
        "name": "Almond", 
        "rgb": "(239, 222, 205)"
    }, 
    {
        "hex": "#CD9575", 
        "name": "Antique Brass", 
        "rgb": "(205, 149, 117)"
    }, 
    {
        "hex": "#FDD9B5", 
        "name": "Apricot", 
        "rgb": "(253, 217, 181)"
    }, 
    {
        "hex": "#78DBE2", 
        "name": "Aquamarine", 
        "rgb": "(120, 219, 226)"
    }, 
    {
        "hex": "#87A96B", 
        "name": "Asparagus", 
        "rgb": "(135, 169, 107)"
    }, 
    {
        "hex": "#FFA474", 
        "name": "Atomic Tangerine", 
...

Get the full list of crayola colors in JSON format

Diagrama de entrada de cine

Usabilidad de las entradas del cine

Ayer fuí a ver Misión Imposible a Cineplanet. Como es de costumbre, hice una breve cola, fuí amáblemente atendido y recibí el ticket de entrada:

Foto de ticket de Cineplanet

Como siempre, confío plenamente que la entrada es para la función que pedí y procedo a memorizar la información que me confirma la chica que atiende por que va a ser imposible encontrar esos datos en la entrada.

Entrada de cine con secciones identificadas

Como se puede ver gran parte de el papel está destinado a llevar información que como cliente no me es importante, y haciendo cálculos aproximadamente sólo el 4.5% del área del papel tiene datos que me interesan.

Por qué no pueden hacer algo más parecido a esto? Incluso en blanco y negro.

Diagrama de entrada de cine

No interesa si adicionalmente me entregan un comprobante de pago y si usan toooda la parte de atrás para poner publicidad y letras pequeñas.

No creería que siguen haciendo lo mismo sólo por que es más difícil de imprimir!

Como agregar un campo a todos los elementos en una collección Mongo

Lo acabo de poner en inglés., pero también lo buscarán en español. Asó que aquí va.

Escribo esto por que encontrar la respuesta me tomó más de lo que esperaba. Finalmente estaba en StackOverflow, pero la pondré acá de nuevo explicando como funciona.

Como las bases de datos Mongo no tienen esquema, no existe comando ALTER TABLE para agregar un nuevo campo a todos los elementos, lo que se hace es actualizar la colección por medio del comando update.

La documentación de Update es muy escasa al respecto y el mapeo de SQL a Mongo tampoco indica nada al respecto.

Así es como se hace una modificación a todos los elementos sin ninguna condición en particular:

db.collection.update( criteria, objNew, upsert, multi )

Queremos actializar todos así que nuestra condición será un objeto vacío.

{}

Queremos añadir un nuevo atributo a todos los objetos, así que usaremos la clave “$set” para hacerlo. El valor que mandemos tendrá la forma de un documento que combinaremos con cada uno de los elementos.

{'$set': {new_key:value}}

No queremos Upsert, asi que vamos a poner False ahí. Si mandaramos True, además de modificar los documentos, agregaríamos un nuevo elemento a al colección con el documento que estamos enviando como dato, y eso no queremos.

En multi, decimos que sí: True, esto es necesario para que se actualice toda la colección y no sólo el primer elemento.

El comando quedaríá así:

db.collection.update( {}, {'$set': {new_key:value}}, false, true)

Add a key to all items on a MongoDB collection

Again, I am posting this because it took me more than expected to find this easy answer. I found it on StackOverflow, but I will repost and explain here.

Since Mongo is a schemaless database, there is no “ALTER TABLE“, so what you need to do is update all the items.

The MongoDB documentation on Updates is not very clear on how to do this. And the SQL to Mongo mapping doesn’t explain this either.

So, here’s how you do it. You perform an update with empty criteria

db.collection.update( criteria, objNew, upsert, multi )

We want to update all the elements, so we use empty criteria

{}

We want to add an attribute, so we will $set the key, it will be in the form of a document to be “merged” with each item.

{'$set': {new_key:value}}

We don’t want upsert. So we set that to False, if we set it to true, the update call will add an item to the collection containing the value we wanted to set and nothing more, which is not what we want.

For multi, we will say True, because we want the update to happen on all the collection item’s and not just the first one.

db.collection.update( {}, {'$set': {new_key:value}}, false, true)
Picture side by side of a toy in color and sepiia

Sepia images with Django, Python and Sorl-thumbnail

Picture side by side of a toy in color and sepiia

Meet Sorl-sepia, a Sorl engine backend (PIL only so far) to turn your images into sepia tones. See the README file for instructions.

The interesting trick about sepia images is that they are just gray-scale pictures with a different color palette. In this case the sepia color I’m using is #FFF0C0.

Doing this on PIL is quite straight forward (from effbot’s blog):

# You have your PIL Image instance on a 'im' variable

# Convert it to grayscale
im = im.convert('L') # L mode means gray-scale

# Set the sepia palette
im.putpalette(linear_ramp) # will explain this later

# Make RGB again
im = im.convert('RGB') 

And there you have it. Now the linear_ramp variable. It is actually a map of 256 blocks indicating what color to use for each of the possible gray-scale values (white to black). You can see the original blog post on how to build the linear_ramp.

If you just want to turn your images to gray-scale instead of sepia, set sorl-sepia SORL_DEFAULT_SEPIA_TONE setting to (0, 0, 0).