Search code examples
pythondjangomodelpluralizeplural

Django admin model plural mode global settings, not adding suffix 's'


We're now using Django.

And our Language is Chinese.

While you know, In Chinese grammar, the plural case is usually the same as the single case. At least, not just adding an English letter 's' after the word.

So, Since we've set the verbose_name of every Model classes as Chinese, and found that in the admin panel, all Models are displays as XXs.

Now we have to set the plural manually, just the same as the verbose_name itself:

class Meta:
    db_table = 'the_table_name'
    verbose_name = 'object_name'
    verbose_name_plural = 'object_name'

So, is there any way to set the global plural transform rules?


Solution

  • Specifying 'verbose_name_plural' is the simple way to override the meta option in django models. But if you want to set it programatically, then you can do this by defining your own meta class like this:

    from django.db.models.base import ModelBase
    
    class CustomModelMetaClass(ModelBase):
    
        def __new__(cls, name, bases, attrs):
            klas = super(CustomModelMetaClass, cls).__new__(cls, name, bases, attrs)
            klas._meta.verbose_name_plural = klas._meta.verbose_name
    
            return klas
    

    Now use this meta class in your models like this

    class Poll(models.Model):
        question = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
        __metaclass__ = CustomModelMetaClass
    

    It will set the verbose_name_plural same as verbose_name. To validate this open shell, import model Poll and print

    unicode(Poll._meta.verbose_name_plural)
    unicode(Poll._meta.verbose_name)