简体   繁体   中英

How to localize django_tables2 column names?

I have used django_tables2 in my web page to display a table.

My code for this table is in tables.py:

import django_tables2 as tables
from django.utils.translation import ugettext_lazy
from django.utils.encoding import force_text

    class patchTable(tables.Table):
        release_version=tables.Column(verbose_name=force_text(ugettext_lazy("Release Version"),orderable=False, localize=True)
        patch_version=tables.Column(verbose_name=force_text(ugettext_lazy("Patch Version")),orderable=False, localize=True)
        release_date = tables.Column(verbose_name=force_text(ugettext_lazy("Release Date")),orderable=False, localize=True)
        upload_date = tables.Column(verbose_name=force_text(ugettext_lazy("Upload Date")),orderable=False, localize=True)
        apply_status = tables.Column(verbose_name=force_text(ugettext_lazy("Status")),orderable=False, localize=True)
        installation_date = tables.Column(verbose_name=force_text(ugettext_lazy("Installation Date")),orderable=False, localize=True)

In my views.py method i am doing "from myapp.tables import patchTable" and then updating the table contents,paginating and rendering to a template.

Above code works fine and displays the column name in a language which is currently i am using(during runserver command). but if i change the language selection on my HTML page all other contents on page gets translated but column name of this table doesn't.

If i restart the django server (cntrl+c and python2.7 manage runserver 0.0.0.0:8060) then these names changes to current language but they are not happening dynamically on language selection.

I tried using 1) "ugettext" 2) "ugettext_lazy" (this throws exception:'Lazy object returned unexpected type.)' 3) "force_text" and "ugettext_lazy" combination. But they are not working. Can anyone suggest me a feasible way of doing it?

By the way I am using Python 2.7, Django 1.5.1 and Django development server. All the localization settings requirement are included in project and settings.py has "USE_L10N = True" and "USE_I18N = True". Any help would be appreciated. Please let me know if this question needs much more details. Thanks in advance.

Under class patchTable(tables.Table): , please add this:

def __init__(self, *args, **kwargs):
        super(patchTable, self).__init__(*args, **kwargs)

__init__ is a constructor, so when the class is called, an object of that Class will be created. Details here .

I re-wrote the code as,

class test():
    _name = None
    def __init__(self, name):
        self._name = name

    def __unicode__(self):
        english_string = get_string()
        params = {}
        params = deepcopy(english_string)
        var = force_text(params['patch_text'][self._name])
        return unicode(var )

class patchTable(tables.Table):

    release_version = tables.Column(verbose_name=test('release_version'),orderable=False)
    patch_version = tables.Column(verbose_name=test('patch_version'),orderable=False)
    release_date = tables.Column(verbose_name=test('release_date'),orderable=False)
    upload_date = tables.Column(verbose_name=test('upload_date'),orderable=False)
    apply_status = tables.Column(verbose_name=test('status'),orderable=False)
    installation_date = tables.Column(verbose_name=test('installation_date'),orderable=False)
    class Meta:
        attrs = {"class": "paleblue", "id":"patch_details", "style":"cursor: pointer;"}
        orderable = False

get_string() is a function that returns translated strings as key value pair. keys are nothing but the column names, values are their respective translated strings(changes on language selection). verbose name is defined by class test() which initializes column names for each new object. init with unicode helped me to solve this.

Thanks to @ruddra and @VikasVerma, Your suggestions helped me.

A general solution for tables based on a model:

class TranslatedTable(tables.Table):
def __init__(self, *args, **kwargs):
    super(TranslatedTable, self).__init__(*args, **kwargs)
    for column in self.base_columns:
            self.base_columns[column].verbose_name = \
                self.Meta.model._meta.get_field(column).verbose_name

The column headers will be defined by verbose_name of the corresponding field and properly translated. Note that verbose_name in this case should be decorated for translation in the model definition, for example:

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

class SomeModel(models.Model):
    name = models.CharField(max_length=100, verbose_name=_("Name"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM