Django is missing TEMPLATE_STRING_IF_NONE

IMO Django is missing a setting TEMPLATE_STRING_IF_INVALID that you cold set to globally override how None value is rendered.

Some argue that you should:

  1. plan to always have a value — ?! what a perverted idea, all fields required
  2. use empty string as a default — django does that, I do not like it, form fields return empty strings for empty fields
  3. use default_if_none filter — to much typing
  4. use if tag — see 3.

There is a difference between empty string value and no having value at all. But in templates in most cases there is not, and django handles it backwards — it differentiate these in templates but in actual data model None is defaulted to empty string.

Not having a value at all — hence None — mean you do not have to store metadata for a filed, which is good for rg. in GAE.

Put this in your main.py — where you initialize wsgi application — to render empty string for None valued variables:

# Patch template Variable to output empty string for None values
from django.template.base import Variable
_resolve_lookup = Variable._resolve_lookup
def new_resolve_lookup(self, *args, **kwargs):
  o = _resolve_lookup(self, *args, **kwargs)
  return o or u""
Variable._resolve_lookup = new_resolve_lookup
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s