带有django翻译字段的多语言翻译

时间:2019-05-04 13:29:59

标签: django django-models django-views

我正试图在django-translated-fields的帮助下建立一个多语言的Django网站。

我正在研究的项目基于cookiecutter-django和Docker。

对于我的模型字段,翻译工作正常-除了提交的子弹。其实slug的翻译也可以,但是我无法在slug领域获得一个条目。

投票模式摘要:

import test1

test1.main(["-tid", "CHEMBL8868", "-molfile", "ligands.sdf"])
test1.main(["-tid", "CHEMBL8293", "-molfile", "stuff.sdf"])
# etc

完整的项目投票模型可见here

视图摘录:

    string identifier;
    identifier.resize(4);

    ifstream adtFile(m_nameFile, ios::in | ios::binary);

    adtFile.read((char*)&identifier, sizeof(::uint32_t));

可以看到here的全视图

由于Django翻译字段创建了class Voting(models.Model): slug = TranslatedField( models.SlugField( max_length=80, unique=True, verbose_name="Voting URL slug", blank=True ), { "de": {"blank": True}, "fr": {"blank": True}, "it": {"blank": True}, "rm": {"blank": True}, "en": {"blank": True}, }, ) def voting(request, slug): voting = get_object_or_404(Voting, slug=slug) context = { 'voting': voting } return render(request, 'votes/single.html', context) ,依此类推,所以我找不到解决方案来获取相应语言的代码。

这很明显,因为Django翻译字段的文档说:

实际上没有创建任何模型字段。 TranslatedField实例是一个描述符,默认情况下充当当前语言字段的属性。

不幸的是,无论如何不要得到它。知道如何更改投票模式以获取特定语言的参赛作品吗?

2 个答案:

答案 0 :(得分:1)

from translated_fields import to_attribute

def voting(request, slug):
    voting = get_object_or_404(Voting, **{to_attribute(name='slug'): slug})
    context = {
        'voting': voting
    }
    return render(request, 'votes/single.html', context)

如有必要,您可以将language_code=request.LANGUAGE_CODE添加到对to_attribute的呼叫中,但是通常这不是必需的:

    voting = get_object_or_404(Voting, **{to_attribute(name='slug', language_code=request.LANGUAGE_CODE): slug})

答案 1 :(得分:0)

不确定这是否正确,但是借助Django文档“ How Django discovers language preference”,我找到了以下解决方案。

按如下所示更改投票视图:

def voting(request, slug):
    '''Takes slug of single voting and returns that voting object in
    corresponding language.
    '''
    if request.LANGUAGE_CODE == 'de':
        voting = get_object_or_404(Voting, slug_de=slug)
    elif request.LANGUAGE_CODE == 'fr':
        voting = get_object_or_404(Voting, slug_fr=slug)
    elif request.LANGUAGE_CODE == 'it':
        voting = get_object_or_404(Voting, slug_it=slug)
    elif request.LANGUAGE_CODE == 'rm':
        voting = get_object_or_404(Voting, slug_rm=slug)
    elif request.LANGUAGE_CODE == 'en':
        voting = get_object_or_404(Voting, slug_en=slug)
    context = {
        'voting': voting
    }
    return render(request, 'votes/single.html', context)