Git Product home page Git Product logo

django-translated-fields's Introduction

django-translated-fields

CI Status

Django model translation without magic-inflicted pain.

Installation

Install the package into your virtualenv:

pip install django-translated-fields

Add the package to your INSTALLED_APPS:

INSTALLED_APPS = [
    *INSTALLED_APPS,
    "translated_fields",
]

django-translated-fields supports all versions of Django from 3.2 to 5.1. If in doubt, check the test runs in the GitHub actions environment.

Usage

You should define the the list of languages your project supports in your settings first by defining LANGUAGES. Otherwise, you'll get fields for all the dozens of languages Django supports out of the box.

Next, add translated fields to your models:

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

from translated_fields import TranslatedField

class Question(models.Model):
    question = TranslatedField(
        models.CharField(_("question"), max_length=200),
    )
    answer = TranslatedField(
        models.CharField(_("answer"), max_length=200),
    )

    def __str__(self):
        return self.question

Basic usage

Model fields are automatically created from the field passed to TranslatedField, one field per language. For example, with LANGUAGES = [("en", "English"), ("de", "German"), ("fr", "French")], the following list of fields would be created: question_en, question_de, question_fr, answer_en, answer_de, and answer_fr.

This implies that when changing LANGUAGES you'll have to run makemigrations and migrate too.

No question or answer model field is actually created. The TranslatedField instance is a descriptor which by default acts as a property for the current language's field:

from django.utils.translation import override

question = Question(
    question_en="How are you?",
    question_de="Wie geht es Dir?",
    question_fr="Ça va?",
)

# The default getter automatically returns the value
# in the current language:
with override("en"):
    assert question.question == "How are you?"

with override("de"):
    assert question.question == "Wie geht es Dir?"

# The default setter can also be used to set the value
# in the current language:
with override("fr"):
    question.question = "Comment vas-tu?"

assert question.question_fr == "Comment vas-tu?"

TranslatedField has a fields attribute that returns a list of all the language fields created.

assert Question.answer.fields == ["answer_en", "answer_de", "answer_fr"]

For more attributes look at the ``TranslatedField`` instance API section below.

question and answer can only be used with model instances, they do not exist in the database. If you want to use queryset methods which reference individual translated fields you have to use language-specific field names yourself. If you wanted to fetch only the english question and answer fields you could do this as follows:

questions = Question.objects.values_list("question_en", "answer_en")

Or better yet, using the to_attribute helper which automatically uses the active language (if you don't pass a specific language code as its second argument):

from django.utils.translation import override
from translated_fields import to_attribute

with override("en"):
    questions = Question.objects.values_list(
        to_attribute("question"), to_attribute("answer")
    )

Changing field attributes per language

It is sometimes useful to have slightly differing model fields per language, e.g. for making the primary language mandatory. This can be achieved by passing a dictionary with keyword arguments per language as the second positional argument to TranslatedField.

For example, if you add a language to LANGUAGES when a site is already running, it might be useful to make the new language non-mandatory to simplify editing already existing data through Django's administration interface.

The following example adds blank=True to the spanish field:

from translated_fields import TranslatedField

class Question(models.Model):
    question = TranslatedField(
        models.CharField(_("question"), max_length=200),
        {"es": {"blank": True}},
    )

Overriding attribute access (defaults, fallbacks)

There are no default values or fallbacks, only a wrapped attribute access. The default attribute getter and setter functions simply return or set the field for the current language (as returned by django.utils.translation.get_language). The default getter falls back to the first language of the field in case get_language() returns None. Apart from that the default getter has no safetyfeatures and may raise an AttributeError and the setter might set an attribute on the model instance not related to a model field.

Both getters and setters can be overridden by specifying your own attrgetter and attrsetter functions. If you want to always fallback to the default language and allow other languages' fields to be empty you can use the TranslatedFieldWithFallback:

from translated_fields import TranslatedFieldWithFallback

class Question(models.Model):
    question = TranslatedFieldWithFallback(
        models.CharField(_("question"), max_length=200),
    )

What it does is: It adds a question field for all languages and automatically falls back to the first defined language if the current language's field is left empty or if no language is activated at all. It also sets blank=True on all field instances except for the first. Since this is such a common use case the TranslatedFieldWithFallback can be used directly, or you can use the translated_fields.utils.fallback_to_default attrgetter.

A different use case might require falling back to any language, this is handled by the bundled translated_fields.utils.fallback_to_any attrgetter.

A different use case might be when you're using locales with region codes such as fr-fr where you want to fall back to the language without a region code. An example attrgetter implementation follows:

from translated_fields import to_attribute

def fallback_to_all_regions(name, field):
    def getter(self):
        value = getattr(self, to_attribute(name), None)
        if value:
            return value
        return getattr(self, to_attribute(name, get_language().split("-")[0]))

    return getter

A custom attrsetter which always sets all fields follows (probably not very useful, but hopefully instructive):

def set_all_fields(name, field):
    def setter(self, value):
        for field in field.fields:
            setattr(self, field, value)
    return setter

TranslatedField instance API

The TranslatedField descriptor has a few useful attributes (sticking with the model and field from the examples above):

  • Question.question.fields contains the names of all automatically generated fields, e.g. ["question_en", "question_...", ...].
  • Question.question.languages is the list of language codes.
  • Question.question.short_description is set to the verbose_name of the base field, so that the translatable attribute can be nicely used e.g. in ModelAdmin.list_display.

Using a different set of languages

It is also possible to override the list of language codes used, for example if you want to translate a sub- or superset of settings.LANGUAGES. Combined with attrgetter and attrsetter there is nothing stopping you from using this field for a different kind of translations, not necessarily bound to django.utils.translation or even languages at all.

Translated attributes without model field creation

If model field creation is not desired, you may also use the translated_attributes class decorator. This only creates the attribute getter property:

from translated_fields import translated_attributes

@translated_attributes("attribute", "anything", ...)
class Test(object):
    attribute_en = "some value"
    attribute_de = "some other value"

Model admin support

The TranslatedFieldAdmin class adds the respective language to the label of individual fields. Instead of three fields named "Question" you'll get the fields "Question [en]", "Question [de]" and "Question [fr]". It intentionally offers no functionality except for modifying the label of fields:

from django.contrib import admin
from translated_fields import TranslatedFieldAdmin
from .models import Question

@admin.register(Question)
class QuestionAdmin(TranslatedFieldAdmin, admin.ModelAdmin):
    pass

# For inlines:
# class SomeInline(TranslatedFieldAdmin, admin.StackedInline):
#     ...

As mentioned above, the fields attribute on the TranslatedField instance contains the list of generated fields. This may be useful if you want to customize various aspects of the ModelAdmin subclass. An example showing various techniques follows:

from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from translated_fields import TranslatedFieldAdmin, to_attribute
from .models import Question

@admin.register(Question)
class QuestionAdmin(TranslatedFieldAdmin, admin.ModelAdmin):
    # Pack question and answer fields into their own fieldsets:
    fieldsets = [
        (_("question"), {"fields": Question.question.fields}),
        (_("answer"), {"fields": Question.answer.fields}),
    ]

    # Show all fields in the changelist:
    list_display = [
        *Question.question.fields,
        *Question.answer.fields
    ]

    # Order by current language's question field:
    def get_ordering(self, request):
        return [to_attribute("question")]

Note

It's strongly recommended to set the verbose_name of fields when using TranslatedFieldAdmin, the first argument of most model fields. Otherwise, you'll get duplicated languages, e.g. "Question en [en]".

Forms

django-translated-fields provides a helper when you want form fields' labels to contain the language code. If this sounds useful to you do this:

from django import forms
from translated_fields.utils import language_code_formfield_callback
from .models import Question

class QuestionForm(forms.ModelForm):

    class Meta:
        model = Question
        fields = [
            *Question.question.fields,
            *Question.answer.fields
        ]
        # Supported starting with Django 4.2: (Previously it was supported
        # directly on the modelform class, but only as an implementation
        # detail https://code.djangoproject.com/ticket/26456)
        formfield_callback = language_code_formfield_callback

You may also globally configure language code labels to be shown within a block:

from translated_fields import show_language_code

def view(request):
    form = ...
    with show_language_code(True):
        return render(request, "...", {"form": form})

Please note that the response has to be rendered within the show_language_code block. This doesn't happen automatically when using Django's TemplateResponse objects.

Other features

There is no support for automatically referencing the current language's field in queries or automatically adding fields to admin fieldsets and whatnot. The code required for these features isn't too hard to write, but it is hard to maintain down the road which contradicts my goal of writing low maintenance software. Still, feedback and pull requests are very welcome! Please run the style checks and test suite locally before submitting a pull request though -- all that this requires is running tox.

django-translated-fields's People

Contributors

adamchainz avatar jghyllebert avatar matthiask avatar raratiru avatar tom-hubrecht avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-translated-fields's Issues

Requesting version bump on PyPI

@matthiask

I am being a total hypocrite here - I am very behind on updating my own packages, so I really hope this doesn't come across as pushy, because I know how much time, effort, and mental energy these seemingly simple things take.

There are some valid reasons to consider pushing a new release of django-translated-fields to PyPI:

  • There have been almost 20 commits since version 0.12.0 was pushed to PyPI. While most don't affect the package itself (changes to tests, action, configuration files, etc), the sum of them surely contains enough work to warrant a version bump.
  • The updates you have made do not reflect on PyPI. For instance, pyproject.toml was updated to add classifiers for Python 3.11 and 3.12, but that is not yet reflected on the package info page on PyPI. The change to the docs in April was very helpful, and while someone going to the repo will see it, anyone looking at the PyPI page will not. You've put a lot of work into the package, and continue to do so, but from the perspective of someone visiting PyPI to assess which translation package to use, it looks like the project has stagnated.
  • And the selfish reason: I really like this package and want to use it as a dependency for another django package I'm developing, but it doesn't feel right to introduce a 3rd party dependency that 'has not been updated in over 2 years' (despite the fact that I know it works as-is with current versions of Django, and that development has continued on the package).

If there is anything blocking a new release that I could help with, please let me know and I will gladly work on a PR I am capable of resolving the blocker.

(And thanks for a great translation package - it has made a great deal of my work easier and has made my application better!)

Integrating DRF Serializers?

Hello Matthias! I'm importing json data through drf serializers into database (using drf serializers for the sake of data validation and code decoupling) . DRF Serializers create corresponding field for every language if it was not set explicitly for the serializer. So my solution is to set explicit field for DRF Serializer. But I like how the problem is solved with the models. Just refer to a field and behind the scene it uses correct language field. Do you think it's possible to make work DRF Serializers that way? I mean, can you please suggest a way how it can be done?

Fallback for locales like Django does (fr_fr to fr ?)

Hi,

If I set up TranslatedFields using LANGUAGES = [('fr', 'French'), ('en' , 'English')], and I define the LANGUAGE_CODE as fr-fr or en-us, the default configuration fails to find the attributes (looking for attr_fr_fr or attr_en_us, thus, failing).

The default behavior for i18n is usually to try the more specific language and then the more generic one, but as I read about your way of handling your dev (that I quite embrace and like :)) I wonder if it's on purpose or not!

What would be nice here, is to have something similar to gettext way, i.e. looking for attribute_fr_fr and if not found, fall back to attribute_fr. I'm willing to give it a try myself but I don't want to start hacking if you don't like the idea.

Regards,
Gilou

Release a django app with translated fields as an option

This is not actually an issue, rather than a theoretical question with big practical impact, inspired from this strategic choice:

This package does not support adding translation functionality "from the outside" because that's exactly the thing which makes django-modeltranslation's code so brittle and costly to maintain.

My "about-to-be-released on github" django app creates a table like the following:

from django.db import models 


class TheFollowing(models.Model):
    blah = models.TextField()

How can I provide the option of using django-translated-fields, if the user who installs my app wants the new field translated? The idea is to also cater for another user who does not want or need any translation happening out of the box.

Is this programmatically feasible or is it better to release two apps, one with translated field and one without?

Trying to override verbose_name to magically export a language aware json schema from model

The idea is to use django-ninja to automatically create a json schema from my model to feed react-jsonschema-form.

The line that fetches the title is using verbose_name. I tried to override verbose_name:

class Test(models.Model):
    point_name = TranslatedField(
        models.CharField(
            max_length=63,
            verbose_name=_("Point Name"),
        ),
        {"el": {"verbose_name": "Point Name (el)"}},
    )

With no luck as expected:

from ninja.orm import create_schema
from my.models import Test

schema = create_schema(Test)
schema.schema()

>>> {'title': 'Test',
 'type': 'object',
 'properties': {'id': {'title': 'Id', 'type': 'integer'},
  'point_name_en': {'title': 'Point Name', 'maxLength': 63, 'type': 'string'},
  'point_name_el': {'title': 'Point Name', 'maxLength': 63, 'type': 'string'}}}

I can, of course do it manually, or use djantic to override the relevant fields and set the title.

Since all that seems to be a rather new technological mindset, related to tools like pydantic, FastApi and SQLAlchemy... I just wanted to say hallo wondering if there is something like a small change that could make the leap.

TranslatedFieldWithFallback questions

I have two questions regarding translated_fields.utils.TranslatedFieldWithFallback:

  1. 
    class MyModel(models.Model):
        name = TranslatedFieldWithFallback(
            models.CharField(max_length=55, blank=True),
        )
        surname = TranslatedFieldWithFallback(
            models.CharField(max_length=55),
        )
    
    

If the default language is 'en' an error will raise when surname_en is empty.

However, if name_en (which can be blank) is empty and name_<another_language> is not empty, the fallback value will be None although in another language, a value may exist.

Is this an intended behaviour?

  1. def fallback_to_default(name):
    def getter(self):
    return getattr(self, to_attribute(name)) or getattr(
    self, to_attribute(name, settings.LANGUAGES[0][0])
    )

    Instead of settings.LANGUAGES[0][0] LANGUAGE_CODE wouldn't it be more straightforward?

    Update
    LANGUAGE_CODE may not be the best option since it defaults to 'en-us' and not just 'en'.

The readme needs a little howto

I don't easily see from the fields-code how to use the field. Could you add a little howto? What to put into the field, how to get the data back out?

Support Django 3.1

django-translated-fields doesn't work with Django 3.1 alpha 1.

I installed Django 3.1 alpha 1 with pip install --upgrade --pre django, but my project can't run even make_migrations or migrate. I receive an exception when I try to import from translated_fields import to_attribute.

I'm using django-translated-fields==0.8.0.

[Question] Is is possible to translate Django's Permission model (the name)

I know the issue tracker is not always the right place for a question, but we would like to migrate our app that uses django-modeltranslation to Django version 2.1. Since modeltranslations is currently unmaintained, and only support Django 1.11 (more or less), we are thinking about using this package.

I think it has everything we need (apart maybe from some glue code which is easy to create), except support for multi-language permissions (contrib.auth.model.Permission.name), am I correct?

Do you maybe have any idea how to circumvent this issue?

Unable to roll back migration

If I simply add TranslatedField(...) around my field and nothing more, when running python manage.py makemigrations, then it will ask if I am renaming my field "name" to either "name_de", "name_en", "name_fr". If I say "yes" to any of one, then I can rollback easily.

However, if I also (1) add verbose_name and (2) remove help_text, makemigrations will consider the changes as (a) removing "name" fields and (b) add three "name_xx" fields. The final migration py, however, cannot roll back:

Migrations for 'myapp':
  myapp/migrations/0006_auto_20180908_1018.py
    - Remove field name from category
    - Add field name_de to category
    - Add field name_en to category
    - Add field name_fr to category

0006_auto_20180908_1018.py:

# Generated by Django 2.1.1 on 2018-09-08 10:18

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0005_auto_20180907_1954'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='category',
            name='name',
        ),
        migrations.AddField(
            model_name='category',
            name='name_de',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='category',
            name='name_en',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='category',
            name='name_fr',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
    ]

When I tried to rollback, error occurs: django.db.utils.IntegrityError: column "name" contains null values.

To fix this, (i) change migrations.RemoveField to migrations.RenameField and (ii) change one of migrations.AddField to migrations.AlterField:

# Generated by Django 2.1.1 on 2018-09-08 10:18

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0005_auto_20180907_1954'),
    ]

    operations = [
        migrations.RenameField(
            model_name='category',
            old_name='name',
            new_name='name_en',
        ),
        migrations.AddField(
            model_name='category',
            name='name_de',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='category',
            name='name_en',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='category',
            name='name_fr',
            field=models.CharField(default='', max_length=100, verbose_name='name'),
            preserve_default=False,
        ),
    ]

Order by automcailly

Thank you for this great package,

I was wondering how I can do order_by on filter

def to_representation(self, instance):
categories = CategorySerializer(Category.objects.all().order_by('name'), many=True).data - True
categories = CategorySerializer(Category.objects.all().order_by('name_en'), many=True).data - False

Status Unknown

I am currently using the "status unknown" django-modeltranslation which seems to be a stalled project, barely working with django-1.11, despite the efforts.

Inspired from the concept of low maintenance software I decided to start my project from scratch with this concept in my mind, this time (thank you for the inspiration).

I agree that the 'status unknown' django-nece is a very interesting approach, however django-translated-fields should be my choice especially for the idea of the descriptor and for the following reasoning:

And living in a country with four official languages (and english isn’t even one of those) it should be easy to believe that after a few years you’ll have plenty of experience providing users and customers with ways to work with multilingual content, and knowing what is necessary and what isn’t.

Are there any plans for a status change?

Django versions supported

Which versions of Django are supported? And is it possible to specify them on PyPI? I noticed that other packages on PyPI specify which versions of Django are supported.

Passing fields from one instance to another

trying to create an instance of a model and passing to it some fields of another model (all fields passed use "TranslatedField") only the current language is passed and not the current language + the other fields with the other languages

# model
class FirstModel(models.Model):
    name = TranslatedField(models.CharField(  _("name"), max_length=200, default="text"),)
    description = TranslatedField(models.TextField(  _("description"), blank=True,  null=True, default="text" ),)

class SecondModel(models.Model):
    name = TranslatedField(models.CharField(  _("name"), max_length=200, default="text"),)
    description = TranslatedField(models.TextField(  _("description"), blank=True,  null=True, default="text" ),)

# the code that make problem
istance_of_second_Model.description = istance_of_first_Model.description

only one of the fields generated by TranslatedField is passed to the second model and is that of the current language while my goal is to pass "simultaneously" all the fields of all languages

in the documentation I do not understand how to solve this problem, I also tried various approaches but I could not solve for this reason I try to write the problem here

Translated fields in ModelAdmin.list_display_links

If the translated field is used as a link in admin, the generated link is not clickable.

from django.contrib import admin
from translated_fields import TranslatedFieldAdmin
from .models import Book

@admin.register(Book)
class BookAdmin(TranslatedFieldAdmin, admin.ModelAdmin):
    list_display = [*Book.title.fields, "isbn"]
    list_display_links = Book.title.fields

The problem is the code that checks the field exists in the defined list_display_links, here: https://github.com/django/django/blob/master/django/contrib/admin/templatetags/admin_list.py#L220-L225

field_name is not a string, but a function, so the function link_in_col returns False.

<function TranslatedFieldAdmin.translated_field_column.<locals>.value at 0x7f723c42a430>

A similar problem occurs with list_editable fields.

How do I use ModelForm with django-translated-fields?

  1. We used django-modeltranslation on Speedy Net and I want to switch to use django-translated-fields. In Speedy Net we use ModelForms such as SpeedyMatchProfileActivationForm [link]. What is the best way to keep using ModelForms when using django-translated-fields?

  2. Is there a way to start a model, such as User [link], with properties such as first_name and last_name? Or do I have to set the properties in a specific language such as first_name_en and last_name_en? Currently if I start the model with properties such as first_name and last_name I receive an exception. We only start models like this in unit tests as far as I know.

What does en-GB become?

If I read the code correctly an attribute (for example 'name') with language in languages en-GB does only add name_en, but not name_en_gb, right?

Corresponding code:
return re.sub(r"[^a-z0-9_]+", "_", ("%s_%s" % (name, language)).lower())
I'm not a regex expert, so I'm not sure, sorry for the dumb question. This would be a difference with django-modeltranslation we have to adjust for.

not works with search_fields

is there any chance to support searching the key directly

// Works
search_fields = ('name_en','name_de', 'key')
// Not Works
search_fields = ('name', 'key')

Possible to use .values and .values_list ?

Right now, trying to call .values or .values_list on a translated field (by its name without _lang code) will result in a crash. I'm wondering if it is possible easily work around this problem to keep using those functions.

contextvars and immutables - required but not documented

Upgrading django-translated-fields to 0.10.2 (from 0.9.0) with pip installs also contextvars-2.4 and immutables-0.14, but I didn't find it documented in README.rst and CHANGELOG.rst. Are contextvars and immutables required and what is the cause for this change?

Admin - Language ID not visible on readonly fields

If a field is readonly (just a label), the additional Field[lang] label is not added when using TranslatedFieldAdmin.

For example:

class ObjectLogAdmin(TranslatedFieldAdmin, admin.ModelAdmin):
    
    # All readonly
    def get_readonly_fields(self, request, obj=None):
        return [field.name for field in self.opts.local_fields]

Must explicit declare fields in every language in Admin

The package works fine IFF I don't declare fields nor fieldsets in my admin.py. In that case, ModelAdmin will properly include "name_en", "name_de", "name_fr" (three actual fields found in database).

If I declare fields (or fieldsets, for example, to properly group different fields) and use "name" instead of "name_xx", the server returns errors:

FieldError at /admin/marketplace/category/1/change/
Unknown field(s) (name) specified for Category. Check fields/fieldsets/exclude attributes of class CategoryAdmin.

Here is my "settings.py" which declare 3 languages as in example:

LANGUAGE_CODE = 'en'
LANGUAGES = [('en', 'English'), ('de', 'German'), ('fr', 'French')]

My "models.py", for simplicity, I only include on translated field. The actual model I tested has two translate fields (name and short_name), and other support fields (is_active, remarks, created_at, modified_at etc).

class Category(models.Model):
    name = TranslatedField(
        models.CharField(max_length=100, help_text=_("Display name."))
    )

My "admin.py". It works just fine before adding TranslatedFieldAdmin.

@admin.register(models.Category)
class CategoryAdmin(TranslatedFieldAdmin, SortableAdminMixin, admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('id')
        }),
        (_('Details'), {
            'fields': ('name',)
        }),
    )
    add_fieldsets = (
        (None, {
            'fields': ('name',)
        }),
    )
    list_display = ('name', )
    search_fields = ['name', ]
    readonly_fields = ['id', ]

    def get_fieldsets(self, request, obj=None):
        if not obj:
            return self.add_fieldsets
        return super().get_fieldsets(request, obj)

Furthermore, when the listing admin still works, the fields "name" is no longer sortable. It acts if it's a calculated fields. If I change list_display= ('name_en') then sorting is back.

If I change name to name_en in fields and field sets, it works, but the labels become "Name en [en]".

Django-3.1: In to_attribute(), get_language() may return None

def to_attribute(name, language_code=None):
language = language_code or get_language()
return re.sub(r"[^a-z0-9_]+", "_", ("%s_%s" % (name, language)).lower())

According to the docs of get_language():

... Returns None if translations are temporarily deactivated

In my code, I am using to_attribute in a ModelForm:

class PendingConsentForm(forms.ModelForm):
...
    class Meta:
        model = models.Term
        fields = (
            "date_created",
            to_attribute("summary"),
            to_attribute("content"),
            "agree",
        )

After upgrading to Django-3.1, when I ./manage.py migrate in my project, I receive this error:

django.core.exceptions.FieldError: Unknown field(s) (summary_none, content_none) specified for Term

This is because get_language() returns None.

How could this be solved?

Possible solutions in def to_attribute(name, language_code=None):

  • language = get_language() or language_code
  • language = language_code or get_language() or settings.LANGUAGE_CODE

Auto-Detection of Current Language for list_filter in django-translated-fields

Hello,

I have been using django-translated-fields in my projects and I have found it to be a very useful package. Recently, I've come across a potential area of improvement related to the language specification.

In my current setup, I define the 'list_display' field like this:

list_display = ["id", "name"]

This approach automatically detects and applies the current language for displaying strings, which works perfectly.

However, when it comes to the 'list_filter' field, I haven't found a way to automatically set the language:

list_filter = ["status", "par_type_en_us"]
# or
list_filter = ["status", *Champion.par_type.fields]

As you can see, I currently need to manually specify the language ('en_us' in this case) or expand the fields, which isn't ideal.

I am wondering whether there might be a way to incorporate a feature that would automatically detect the current language for the 'list_filter' field, just as it does for 'list_display'? I believe this would make the package even more intuitive and user-friendly.

I look forward to your feedback and potential solutions to this.

Thank you!

filter is not working for the main name

django.core.exceptions.FieldError: Cannot resolve keyword 'name' into field. Choices are: city_id, country, created, daily, hourly, id, latitude, longitude, name_ar, name_de, name_en, name_es, name_fr, name_it, name_nl, name_ru, name_sv, name_tr, name_ua, name_zh_cn, name_zh_tw, state, updated, users, weather

cities.filter(name="test")

any idea to search over all languages with the same key name?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.