Login

Translated choices fields

Author:
anibal
Posted:
July 19, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)
  • Choices are saved as the key integers.
  • Admin will show the correct translation in forms.
  • You can reuse the make_choices function for other choices fields.
  • Bad side: bin/make_messages.py won't get the choices values automatically, you have to add them in the .po's by hand.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.db import models
from django.utils.translation import ugettext_lazy as _

def make_choices(choices):
    """
    Returns tuples of localized choices based on the dict choices parameter.
    Uses lazy translation for choices names.
    """
    return tuple([(k, _(v)) for k, v in choices.items()])

class Quality(models.Model):
    QUALITY_CHOICES = {
        1: 'bad',
        2: 'regular',
        3: 'good',
    }
    q = models.PositiveSmallIntegerField(choices=make_choices(QUALITY_CHOICES))
    class Admin: pass

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.