I just had a formset where each form had a pre-loaded ModelChoiceField, and I needed to display the name of the selected choice in the template. On a model you would just use the get_FOO_display() method, but a form has no such convenience. I found a number of almost solutions on Stack Overflow, and after poring over them I concluded the best solution for my problem was to add the following method to the form:
class QuestionLanguageForm(forms.Form):
''' basic QuestionLanguage form '''
language = forms.ModelChoiceField(queryset=Language.objects.all())
short = forms.CharField()
place_holder = forms.CharField()
long = forms.CharField(widget=forms.Textarea(attrs={'rows':None, 'cols':None}))
def get_language_name(self):
''' returns the name of the selected language '''
try:
return Language.objects.get(id=self.initial['language']).name
except:
return None
This way I can use
{{ form.get_language_name }}
in my template and it prints the human readable name of the language set in my initial data. This code is not robust; I catch all exceptions and ignore them because I’m only using it in a circumstance where this code won’t raise an exception (and in case it does, at least it won’t fail catastrophically). However proper error handling could be added pretty simply. #ExerciseForTheReader
P.S. The title says “selected” value but I’m actually using a pre-loaded value, not anything user selected. If you need to get a user selected value you could use self.data or self.cleaned_data instead of self.initial.