GithubHelp home page GithubHelp logo

bbmokhtari / django-translations Goto Github PK

View Code? Open in Web Editor NEW
135.0 10.0 23.0 2.49 MB

Django model translation for perfectionists with deadlines.

Home Page: http://bbmokhtari.github.io/django-translations

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
django model translation model-translations internationalization localization translations

django-translations's People

Contributors

bbmokhtari avatar danpalmer avatar hramezani avatar urm8 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  avatar  avatar  avatar  avatar  avatar  avatar

django-translations's Issues

clean logic code.

File “.../lib/python3.6/site-packages/translations/management/commands/synctranslations.py", line 76, in get_obsolete_translations
if issubclass(model, Translatable):
TypeError: issubclass() arg 1 must be a class

def get_obsolete_translations(self, content_types):
        r"""Return the obsolete translations of some `ContentType`\ s."""
        if content_types:
            query = Q()
            for content_type in content_types:                                
                model = content_type.model_class()
                if issubclass(model, Translatable):
                    trans_fields = model._get_translatable_fields_names()
                    model_query = (
                        Q(content_type=content_type)
                        &
                        ~Q(field__in=trans_fields)
                    )
    

Take care about NoneType

I have a model created before. Then no longer use it.
i had 3hours to find out
hope this help!

It's better if `TranslatableAdmin` changes the admin form in place, so that there is no need for `TranslationInline`s.

Is your feature request related to a problem? Please describe.
Currently the way to manage the translations in the admin is to inherit the admin from TranslatableAdmin and add TranslationInline as its inline.
It's better if TranslatableAdmin changes the admin form in place, so that there is no need for TranslationInlines.

Describe the solution you'd like
Each translatable field should be duplicated in the admin form for each supported language. so if name is a translatable field, there should be name (en - default), name (de), etc. for all the languages. If the field is required (blank=False) the default language field should be required as well, but not other language fields.
This way the admin inlines can manage translations as well and they are not restricted because of the inline limit issues in Django.

Removing a field from a model cause "Exception Value: '<Model>' object has no attribute '<field>'" in TranslationInline

If the field with some rows in translations_translation table was removed from source of some model,
when we go to the admin with

inlines = [TranslationInline,]

we will get this error
"Exception Value: 'Model' object has no attribute 'field'"
in

source=getattr(self.content_object, self.field),

How to resolve
I think, it is need to add condition to test if self.content_object has field self.field:

source = getattr(self.content_object, self.field) if hasattr(self.content_object, self.field) else self.field

Use Translatable as Mixin or Postgis support?

Currently, I use PostGIS and GeoDjango. This requires to inherit model from from django.contrib.gis.db import models.Model. However, I want to use Translatable too but seems like it's impossible to combine them, right? Thanks

Unsupported lookup 'unaccent'

Can't use postgres unaccent extension on TranslatableQueryset

Unsupported lookup 'unaccent'
/translations/utils.py in _fill_dissected, line 78

My filter: (where qs in a TranslatableQueryset)
qs = qs.filter(Q(name__unaccent__icontains=params.get('q')))

Help?!

TypeError: `abc` is neither a model instance nor an iterable of model instances.

I have a project setup with django 3.2.5 and drf 3.14.0 on python 3.6 and postgres 9.6.
I followed the following steps to create a translatable model for learning products model.

from translations.models import Translatable
class LearningProduct(Translatable):
    title = models.CharField(
        _("Title"),
        max_length=255,
        unique=True
    )
    description = models.TextField(
        _("Description"),
        blank=True,
        null=True
    )
    image = models.ImageField(
        _("Image"),
        upload_to="uploads/images/learning_products/%Y/%m/%d",
        max_length=255,
        blank=True,
        null=True
    )
    link = models.URLField(
        _("Link"),
        blank=True,
        null=True
    )

    class Meta:
        db_table = "learning_product"
        verbose_name = _("Learning Product")
        verbose_name_plural = _("Learning Products")

    class TranslatableMeta:
        fields = ['title', 'description', 'link']
    
    def __str__(self):
        return self.title

added it to the admin panel as follows:

from translations.admin import TranslatableAdmin, TranslationInline

class LearningProductAdmin(TranslatableAdmin):
    inlines = [TranslationInline]

admin.site.register(LearningProduct, LearningProductAdmin)

it lets me save the model's translations for the specified fields. i have two languages setup in my settings as:

## Translation settings.
LANGUAGES = (
    ('en', _('English')),
    ('ne', _('Nepali')),
)

i have my apiview setup as follows and it lets me fetch the model when no accept-language is passed as well as when En is passed as the accept-language but i run into the error given below it when i try get method woth accept-language as Ne.
views.py

# views.py
from rest_framework import generics
from core.models import LearningProduct

class LearningProductSerializer(serializers.ModelSerializer):
    """
    Class to serialize Learning Product data types.
    """

    class Meta:
        model = LearningProduct
        fields = '__all__'

class LearningProductListView(generics.ListAPIView):
    queryset = LearningProduct.objects.all()
    serializer_class = LearningProductSerializer

    def get_queryset(self):
        queryset = super(LearningProductListView, self).get_queryset()
        return queryset.translate_related(
            'title',
            'description',
            'link',
        ).translate()

the error:

[log].ERROR Internal Server Error: /api/v2/learningproducts/
Traceback (most recent call last):
  File "C:\my-site\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\my-site\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\my-site\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\my-site\env\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\generics.py", line 199, in get
    return self.list(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\mixins.py", line 40, in list
    page = self.paginate_queryset(queryset)
  File "C:\my-site\env\lib\site-packages\rest_framework\generics.py", line 171, in paginate_queryset
    return self.paginator.paginate_queryset(queryset, self.request, view=self)
  File "C:\my-site\env\lib\site-packages\rest_framework\pagination.py", line 216, in paginate_queryset
    return list(self.page)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\_collections_abc.py", line 883, in __iter__
    v = self[i]
  File "C:\my-site\env\lib\site-packages\django\core\paginator.py", line 188, in __getitem__
    self.object_list = list(self.object_list)
  File "C:\my-site\env\lib\site-packages\django\db\models\query.py", line 280, in __iter__
    self._fetch_all()
  File "C:\my-site\env\lib\site-packages\translations\querysets.py", line 54, in _fetch_all
    with Context(self._result_cache, *self._trans_rels) \
  File "C:\my-site\env\lib\site-packages\translations\context.py", line 21, in __init__
    self.mapping, self.query = _get_purview(entity, hierarchy)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 199, in _get_purview
    _fill_entity(entity, hierarchy)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 195, in _fill_entity
    _fill_obj(obj)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 190, in _fill_obj
    included=detail['included'],
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 148, in _fill_entity
    iterable, model = _get_entity_details(entity)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 132, in _get_entity_details
    raise TypeError(error_message)
TypeError: `abc` is neither a model instance nor an iterable of model instances.
[log].ERROR Internal Server Error: /api/v2/learningproducts/
Traceback (most recent call last):
  File "C:\my-site\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\my-site\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\my-site\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\my-site\env\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\my-site\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\generics.py", line 199, in get
    return self.list(request, *args, **kwargs)
  File "C:\my-site\env\lib\site-packages\rest_framework\mixins.py", line 40, in list
    page = self.paginate_queryset(queryset)
  File "C:\my-site\env\lib\site-packages\rest_framework\generics.py", line 171, in paginate_queryset
    return self.paginator.paginate_queryset(queryset, self.request, view=self)
  File "C:\my-site\env\lib\site-packages\rest_framework\pagination.py", line 216, in paginate_queryset
    return list(self.page)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\_collections_abc.py", line 883, in __iter__
    v = self[i]
  File "C:\my-site\env\lib\site-packages\django\core\paginator.py", line 188, in __getitem__
    self.object_list = list(self.object_list)
  File "C:\my-site\env\lib\site-packages\django\db\models\query.py", line 280, in __iter__
    self._fetch_all()
  File "C:\my-site\env\lib\site-packages\translations\querysets.py", line 54, in _fetch_all
    with Context(self._result_cache, *self._trans_rels) \
  File "C:\my-site\env\lib\site-packages\translations\context.py", line 21, in __init__
    self.mapping, self.query = _get_purview(entity, hierarchy)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 199, in _get_purview
    _fill_entity(entity, hierarchy)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 195, in _fill_entity
    _fill_obj(obj)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 190, in _fill_obj
    included=detail['included'],
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 148, in _fill_entity
    iterable, model = _get_entity_details(entity)
  File "C:\my-site\env\lib\site-packages\translations\utils.py", line 132, in _get_entity_details
    raise TypeError(error_message)
TypeError: `abc` is neither a model instance nor an iterable of model instances.
[basehttp].ERROR "GET /api/v2/learningproducts/ HTTP/1.1" 500 165340

Unable to delete field translation

Describe the bug

To my knowledge, there is no way to delete a translation for a single field, or to save the original value back over the top of it.

Steps attempted:

  • Setting the field to None within a context.
  • Calling delattr within a context.
  • Setting the field to the original non-translated value.

None of these remove the translation of that field.

There are mechanisms to delete all of the translations relating to a model, but given that translations are on a per-field basis, this creates a mismatch that is hard to work around in custom tooling.

Expected behavior
At the very least, setting a field to the non-translated value should "work", updating the translation to the same value. Ideally this would actually delete the translation, or an API is provided to delete the translation for a given field.

A database connection opened on start-up

Describe the bug

The TranslationsConfig.ready method opens a database connection during start-up. This is behaviour is unexpected and discouraged by Django.

To Reproduce

Run any management command & observer DB queries.

Expected behaviour

Is caching of content types on start-up necessary? The expected behaviour here is for ready() to not make any database queries.

Additional context

This affects all Django versions, though with translations in INSTALLED_APPS as per install instructions only >= 3.2 Django versions are affected (as default_app_config isn't set on the module so TranslationsConfig isn't used by default in < 3.2 Django versions).

Integrate into Wagtail

Hey, this is more an advice's request rather than a feature request.

I am currently trying to integrate your project into a Wagtail project (http://github.com/wagtail/wagtail).
Wagtail uses a different admin than django-admin, so it is not straightforward.

I was wondering if you could lead me to some general concepts regarding your project that could help me build a custom admin in Wagtail based on it.

By the way, thanks a lot for your work, it is very well documented.

Unable to translate records with same foreign keys

Describe the bug
I am trying to translate related fields of a model. but it only translated the first record and skipped the ones which are repeating.

To Reproduce

  1. create a model of Department with fields, department_name and their respective translations
  2. Create a model of employee with foreign key of department
  3. create multiple employees with same department and translate them
  4. you can see issue

Expected behavior
It should translate all the department names

Screenshots
It should translate both the records with 430000000001 number

image

Desktop (please complete the following information):

  • OS: Ubuntu 2020.04
  • Browser chrome

UnboundLocalError is raised by a queryset filtering by Exists

Describe the bug

When filtering the queryset for a translatable model using django.db.models.Exists as the argument to filter, an UnboundLocalError is raised by translations/query.py. When the models are changed to inherit from django.db.models.Model directly instead of translations.models.Translatable, the queryset works as expected.

To Reproduce

Steps to reproduce the behavior:

  1. Go to the sample project and upgrade Django to 3.0 with pip install Django==3.0
  2. Go to the Django shell for the sample project with python project/manage.py shell
  3. Run the following in the shell:
from django.db.models import Exists, OuterRef
from sample.models import Continent, Country
has_countries = Country.objects.filter(continent__pk=OuterRef('pk'))
Continent.objects.filter(Exists(has_countries))
  1. You'll see an exception in the shell like this:
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/path/to/django-translations/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/path/to//django-translations/translations/querysets.py", line 82, in filter
    query = _fetch_translations_query_getter(
  File "/path/to/django-translations/translations/query.py", line 96, in _get_translations_query
    children[index] = q
UnboundLocalError: local variable 'q' referenced before assignment

Expected behavior

With Django 3.0+, and after changing the Country and Continent models in sample/models.py to inherit models.Model instead of Translatable, you will see the following:

>>> Continent.objects.filter(Exists(has_countries))
<QuerySet [<Continent: Europe>, <Continent: Asia>, <Continent: Africa>, <Continent: North America>, <Continent: South America>, <Continent: Australia>]>
>>>

Antarctica doesn't exist in the sample database but I would expect that this query would return successfully and filter out the continent of Antartica if it was added to the continents table but didn't have any countries associated with it.

Desktop (please complete the following information):

  • OS: macOS Big Sur (11.0.1)
  • Python 3.8.7
  • Django 3.0 +
  • Django Translations version 1.2.0

Additional context

This query does not appear to work on Django 2.x used in the sample project. But in Django 3+ it does what I expect.

>>> Continent.objects.create(name='Antarctica')
>>> Continent.objects.all()
<QuerySet [<Continent: Europe>, <Continent: Asia>, <Continent: Africa>, <Continent: North America>, <Continent: South America>, <Continent: Australia>, <Continent: Antarctica>]>
>>> Continent.objects.filter(Exists(has_countries))
<QuerySet [<Continent: Europe>, <Continent: Asia>, <Continent: Africa>, <Continent: North America>, <Continent: South America>, <Continent: Australia>]>
>>>

Setting translation incorrectly

When I want to set a translation in a different language, just one of them is being considered.

I make a request to an endpoint using the following parameters in a test:

params = {
            'introduction': [{'code': 'en', 'translation': 'New introduction'},
                                    {'code': 'es', 'translation': 'Nueva introducción'}],
            . . .
}

What I want to do, is to set different translations at the same time. So in the serializer I'm doing:

    def create(self, validated_data):
        introduction = validated_data.pop('introduction', [])
        process = Process.objects.create(**validated_data)

        with Context(process) as context:
            for introduction_translation in introduction:
                process.introduction = introduction_translation['translation']
                context.update(introduction_translation['code'])

                print("READ es")
                context.read('es')
                print(process.introduction)
                print("READ en")
                context.read('en')
                print(process.introduction)

But sadly, the outputs of the prints are:

READ es
New introduction
READ en
None

READ es
Nueva introducción
READ en
None

It is always setting the translation for the same language (es), but for the other one (en) the translation remains empty.

Is there something I'm doing wrong? Thanks in advance!

Django 3.2.0 Slug field issue

Describe the bug
after upgrading Django 3.2 my slug field is giving None object. this cannot filter with slug_tr.

To Reproduce
Steps to reproduce the behavior:
Everything is same just upgrade to Django 3.2 my multilanguge slug field cannot filter with slug_tr

Expected behavior
It works on Django 3.1.6

Screenshots
image

Desktop (please complete the following information):

  • OS: on local macOS with sqlite it works. Not works on Python 3.7 running on 64bit Amazon Linux 2/3.2.1
  • Browser (Not related)
  • Version [e.g. 22]

I cannot fix the issue so I've go back to Django 3.1.6. I hope this will be fix soon

Postgres support

The project's README indicates that it's not compatible with PostgreSQL, however from experience it seems to in fact work ok. I'm not sure if I'm just not using all the features, but even then it might be useful to have details in the README about what's supported and what isn't.

Is there a record somewhere of what's known to be broken with PostgreSQL?

Can't install from requirements.txt git+git fork: no config.json file

This file config.json is absent indeed.

    Complete output (5 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-6uzaewv5/django-translations_dab4e8f6518542a29e8b41bcf7e9c9bb/setup.py", line 8, in <module>
        with open('config.json', 'r') as fh:
    FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

Translatable field, support not only text;

Is your feature request related to a problem? Please describe.
I am trying to use translation on a model but there is a little problem, model also has an image field and I need to change that image too depending on the language the user is viewing.

Describe the solution you'd like
Maybe supporting a few primitive fields like ImageField / FileField or maybe supporting insertion the input of any field info translation model.

Describe alternatives you've considered
Currently I am not sure and there is not much alternatives and my project is already heavily dependent on django-translations so it would be nice to have that feature, or maybe a model meta hacky thing to insert custom things into text field may help too. Probably I am going to try get image url and fit into translated text field but still, a more generic way would be better.

Additional context
From this:

translation = Translation.objects.create(
    content_type=ContentType.objects.get_for_model(Continent),
    object_id=europe.pk,
    field='name',
    language='de',
    text='Europa',
)

To this (may not be possible that way or may not suitable, just a way to present this mind set):

translation = Translation.objects.create(
    content_type=ContentType.objects.get_for_model(Continent),
    object_id=europe.pk,
    field='name',
    language='de',
    input_field_type=models.ImageField,
    content=Image,
)

Error with relation to models without id

Describe the bug
Error when call

To Reproduce
Steps to reproduce the behavior:

  1. Create a model
  2. Create a relational model (M2M)
  3. Relational must have a custom primary key
name = models.CharField(max_length=50, primary_key=True)
  1. call translate with qs.translate(...).translate_related(...)

Expected behavior
relational models have been translated

Screenshots
cleanshot 2019-03-02 at 12 29 45

Desktop (please complete the following information):

  • OS: MacOS 10.14.3 (18D109)
  • Browser: Chrome Version 73.0.3683.46 (Official Build) beta (64-bit)
  • Version django-translations==1.1.0

Additional context
I think it occurred because of this

object_id = str(obj.id)

Get all translations to JSON-Reponse using rest_framework

Hi...need help

I would like to get a view (ModelViewSet?, ViewSet?, ...) in DRF (Django Rest Framework) that export not only a selected language, but the set of all languages like in django-hvad or django-parler.

  • It is possible to get with this library my desired result?

Today I am able to get a ModelViewSet, that returns the standard-language (in this case 'de')

# /ebp/faqcategory/
[
    {
        "id": 1,
        "is_enable": true,
        "priority": 1,
        "title": "Erste Kategorie"
    },
    {
        "id": 2,
        "is_enable": true,
        "priority": 2,
        "title": "Zweite Kategorie"
    }
]

# /ebp/faqcategory/1/
 {
        "id": 1,
        "is_enable": true,
        "priority": 1,
        "title": "Erste Kategorie"
    }

I didn't unsderstand how I will be able to get similar integrated rest_framework for all the languages.

I mean:

# /ebp/faqcategory/
[
    {
        "id": 1,
        "is_enable": true,
        "priority": 1,
        "translations": {
            "de": {"title": "Erste Kategorie"},
            "fr": {"title": "Première catégorie"},
            "it": {"title": "" },
            "en": {"title": "First category"}
        }
    },
    {
        "id": 2,
        "is_enable": true,
        "priority": 2,
        "translations": {
            "de": {"title": "Zweite Kategorie"},
            "fr": {"title": "Deuxième catégorie"},
            "it": {"title": "" },
            "en": {"title": "Second category"}
        }
    }
]

# /ebp/faqcategory/1/
{
        "id": 1,
        "is_enable": true,
        "priority": 1,
        "translations": {
            "de": {"title": "Erste Kategorie"},
            "fr": {"title": "Première catégorie"},
            "it": {"title": "" },
            "en": {"title": "First category"}
        }
    }

My actual code:

# settings.py
LANGUAGE_CODE = 'de'
LANGUAGES = (
    ('en', 'English'),
    ('de', 'German'),
    ('fr', 'French'),
    ('it', 'Italian'),
)
# models.py
class FaqCategory(Translatable):
    is_enable = models.BooleanField(blank=False, default=False)
    priority = models.IntegerField(blank=False, unique=False, default=-1)
    title = models.CharField(max_length=80, default="")

    def __str__(self):
        return self.title + " ["  + str( self.id ) + "]"

    class Meta:
        ordering = ['priority', 'title']

    class TranslatableMeta: # django-translation
        fields = ['title']
# view.py
from rest_framework import viewsets
from ebp import models
from ebp import serializers

# {{host}}/ebp/faqcategory/
class FaqCategoryViewSet(viewsets.ModelViewSet):
    queryset = models.FaqCategory.objects.all()
    serializer_class = serializers.FaqCategorySerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['id', 'priority', 'title']
#serializers.py
from rest_framework import serializers
from ebp import models

class FaqCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.FaqCategory
        fields = '__all__'

Updating translatable fields via DRF serializer

Hey, is there a specific way you have to update the translatable model fields when using the DRF serializer? When updating through the Context object and the serializer's .save() method, the original values are mistakenly updated as well.

Translation on subsequent instances in the queryset is missing or replaced

In the relationship I describe below, only the last updated ItemTag in the queryset has its 'name' property translated. The rest of the objects that point to the same Tag have their original text. Not sure if it's something I have done wrong and the translation is being replaced or never loaded. Can you shed some light? :)

Steps to reproduce the behavior:
`

class Item(Translatable, models.Model):
    name = models.Charfield(max_length=30)

class Tag(Translatable, models.Model):
    name = models.Charfield(max_length=30)

    class TranslatableMeta:
        fields = ['name']

class ItemTag(Translatable, models.Model):
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
    item= models.ForeignKey(Item, on_delete=models.CASCADE)

    def __str__(self):
        return self.tag.name

    @property
    def name(self):
        return self.tag.name

By retrieving ItemTags with the Tags translated, I notice than only one of the ItemTag instances has correct translation on the name
ItemTag.objects.select_related('tag').translate('gr').translate_related('tag')

lost_in_translation

`

Expected behavior
All ItemTags pointing to the same Tag with translation should have their name displayed as translated

Django 3.0.5
django-translations 1.2.0

When a field is removed from the translatable fields the `Translation` objects for it are not removed.

Describe the bug
When a field is removed from the translatable fields the Translation objects for it are not removed.

To Reproduce
Steps to reproduce the behavior:

  1. Make a model translatable.
  2. Specify at least two translatable fields.
  3. Make admin translatable.
  4. Launch the Django project.
  5. Create an object in the model admin and add translation for all the translatable fields.
  6. Stop the launched Django project.
  7. Remove one of the translatable fields in the model.
  8. Relaunch the Django project.
  9. The translations for the removed translatable field are not deleted as well.

Expected behavior
The removed translatable fields translations should be deleted.

Field _default_translatable_fields leaks through save() and refresh(), breaking context.reset() later on

Describe the bug
In the context of Django Rest Framework for example, "_default_translatable_fields" is populated when queryset loads the instance, modifying it and saving it doesn't change this "_default_translatable_fields" later, so doing a context.reset() later reverts all changes to the instance, even those committed to DB.

To Reproduce
For example if django-translations is used in django-rest-framework, and a post-save signal is used in an update() view call, to automatically update translatiions using a translator webservice, then in the end the instance returned has been reverted to the state before the update().

Expected behavior
We expect context.reset() to get the instance back to the state at the start of the Context(), or maybe revert it to its DB state (like a refresh_from_db()), but not to revert it to a far state form a previous Context() use.

How i can update the translate using the code

i'm trying to do something like that

                de = Map.objects.translate('de-de').filter(map_id=11).update_or_create(
                    map_id=11,
                    defaults={'map_id': 11,
                              'map_name': "test",
                              })

but it won't create or update

No operator matches the given name and argument types. You might need to add explicit type casts.

Describe the bug

When I try to use .probe ot TQ with language I get this weird error. What can be wrong?
`>>> DoctorSpecialization.objects.probe(['ru']).filter(name__contains='рад')
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedFunction: operator does not exist: integer = character varying
LINE 1: ...anslation" ON ("doctor_doctorspecialization"."id" = "transla...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python3.7/site-packages/translations/querysets.py", line 41, in _fetch_all
    super(TranslatableQuerySet, self)._fetch_all()
  File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: operator does not exist: integer = character varying
LINE 1: ...anslation" ON ("doctor_doctorspecialization"."id" = "transla...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

>>> `

Desktop (please complete the following information):

  • Linux

I use the latest version of django-translations and django 2.2.5

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.