[Django]-Django rendering display name of choice field in form

3👍

I got the following answer from reddit user roambe:

Since city is a foreign key, Django will use the __str__ (or __unicode__) method of the City model for the choice label.
This should make it start behaving like you want to (substitute for unicode if needed):

def __str__(self):
    return self.get_name_display()
👤Flobin

1👍

In your line 'city': forms.RadioSelect(),, you need to define the choices for it. It should look like:

from blah.models import City

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'text', 'categories', 'city']
        widgets = {'title': forms.TextInput(attrs={
            'placeholder': 'Enter a descriptive title'}),
            'text': forms.Textarea(attrs={'placeholder': 'The article'}),
            'categories': forms.CheckboxSelectMultiple(),
            'city': forms.RadioSelect(choices=City.CITY_CHOICES),
        }

The radio select widget inherits from the select widget, which has a brief mention of the choices argument in the docs here: https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.Select

0👍

I’d like to extend the argument a little, with a ‘work-around’ solution for an inherit problem.

In my situation, the returned value never changes from ‘value’ to ‘human-r’. I believe it depends on my db-django config: on my db the field is a FK, but on Django is a simple CharField. In this way I can’t define a str method for it without make changes to the model.
I decided, I had only 2-3 choices, to override the get_status function in order to evaluates the status and return a ‘constant’ output (a simply IF construct).

👤Gmarra

Leave a comment