django internationalization: counter is not available when marking strings for pluralization

情到浓时终转凉″ 提交于 2019-12-12 01:37:59

问题


Adding plural to django stings in the code should use ungettext(), where the 3rd parameter is the counter to decide whether it should use singular or plural:

text = ungettext(
        'There is %(count)d %(name)s available.',
        'There are %(count)d %(name)s available.',
        count
) % {
    'count': count,
    'name': name
}

The parameter as counter should be available when ungettext() is called. But in my case, the string and the counter is separated so it's impossible to supply the counter at the right place:

class foo(bar):
    description="There is %(count)d %(names)s available."

class foo_2(bar):
    description="%(count)d rabbits jump over the %(names)s."

# More 'foo' type classes....

class foo_model(Model):
    count=IntegerField()
    name=CharField()
    klass=CharField()
    #model definition...

    def _get_self_class(self):
        if self.klass=='foo':
            return foo
        elif self.klass=='foo_2':
            return foo_2

    def get_description(self):
            return self._get_self_class.description%(self.count,self.name)

I'm a bit of stuck with how to internationalize this. Does anybody has a good idea?

Update:

I've changed the example to a closer match of my situation


回答1:


You need to construct ungettext somewhere, for example

class Foo(Bar):
    description = "There is %(count)d %(names)s available."
    description_plural = "There are %(count)d %(names)s available."

class FooModel(Model):
    count = IntegerField()
    name = CharField()
    # model definition...

    def get_description(self):
        return ungettext(Foo.description, Foo.description_plural, self.count) % \
                   {'count':self.count, 'name':self.name}


来源:https://stackoverflow.com/questions/10517683/django-internationalization-counter-is-not-available-when-marking-strings-for-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!