[Answered ]-In Django, in a form, how to dynamically choose custom Model field to be displayed in a ModelChoiceField?

1👍

Dude, if you want to make a translation of what is known as verbose_name, ideally u use the django internationalization.

The documentation in the following link: https://docs.djangoproject.com/en/dev/topics/i18n/translation/

1👍

I finally found a way, using the work described by Beau Simensen : http://srcmvn.com/blog/2013/01/15/django-advanced-model-choice-field/ who modified ModelChoiceField to return (value,label,model) instead of (value,label).

So far, seems to work OK for me.

from django.forms import models
from django.forms.fields import ChoiceField

class AdvancedModelChoiceIterator(models.ModelChoiceIterator):
    def choice(self, obj):
        return (self.field.prepare_value(obj), self.field.label_from_instance(obj), obj)

class AdvancedModelChoiceField(models.ModelChoiceField):
    def _get_choices(self):
        if hasattr(self, '_choices'):
            return self._choices

        return AdvancedModelChoiceIterator(self)

    choices = property(_get_choices, ChoiceField._set_choices)
👤nolnol

Leave a comment