Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Last active July 5, 2023 14:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumepiot/3c10af3ca73036f2757e to your computer and use it in GitHub Desktop.
Save guillaumepiot/3c10af3ca73036f2757e to your computer and use it in GitHub Desktop.
Django Form - Custom ModelChoiceField label
from django import forms
from django.utils.safestring import mark_safe
class CustomModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return mark_safe("My Object custom label <strong>%i</strong>" % obj.id)
class MyForm(forms.ModelForm):
my_field = CustomModelChoiceField(label=_('The form label'), queryset=MyModel.objects.filter(), widget=forms.RadioSelect, empty_label=None)
class Meta:
model = MyModel
@estJune
Copy link

estJune commented Jun 20, 2023

I am sorry, but I am still relatively new to python and Django, what is the purpose of the underscore in line 10 when declaring label?

@curious-broccoli
Copy link

I am sorry, but I am still relatively new to python and Django, what is the purpose of the underscore in line 10 when declaring label?

I think it might be for internationalization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment