Label : django

django / mark_safe / translatables

By | | Tech | Schrijf als eerste een commentaar!

Look at this snippet of Django code in models.py, and in particular the help_text bit:

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe

class MyModel(models.Model):
    my_field = models.CharField(max_length=123,
                                help_text=mark_safe(_('Some <b>help</b> text.')))

For those unfamiliar with Django. A quick run-down:

  • The definition of MyModel creates a mapping between the MyModel class and a underlying app_mymodel table in a database.
  • That table will consist of two columns: id, an automatic integer as primary key (created by default), and my_field, a varchar ...

django / mongodb / manage dbshell

By | | Tech | Schrijf als eerste een commentaar!

The current django-mongodb-engine doesn't seem to ship with a working manage dbshell command yet. Right now it returns this:

$ ./manage.py dbshell
...
  File "/home/walter/.virtualenvs/myproject/lib/python2.6/site-packages/django/core/management/commands/dbshell.py", line 21, in handle
    connection.client.runshell()
  File "/home/walter/.virtualenvs/myproject/lib/python2.6/site-packages/django_mongodb_engine/base.py", line 108, in __getattr__
    raise AttributeError(attr)
AttributeError: client

The fix is simple, patch your django_mongodb_engine with this:

--- django_mongodb_engine/base.py.orig  2011-11-15 11:53:47.000000000 +0100
+++ django_mongodb_engine/base.py 2011-11-15 11:54:07.000000000 +0100
@@ -7,6 +7,7 @@
 from pymongo ...

django / query expression / negate

By | | Tech | 2 commentaren

Suppose you have an is_enabled boolean in your Django model.

class Rule(models.Model):
    is_enabled = models.BooleanField(blank=True)
    # other exciting fields here

And now imagine you want to negate the is_enabled values. Something you would easily do in SQL, with: UPDATE myapp_rule SET is_enabled = NOT is_enabled;

The Django F-syntax is nice, and looks like it should be up for the task.

Let's sum up a couple of attempts:

Rule.objects.update(is_enabled=(not F('is_enabled')))

No! You get this:
UPDATE myapp_rule SET is_enabled = true;

Rule.objects.update(is_enabled=(True ^ F('is_enabled')))

No! You get this:
unsupported operand type ...