How to get help_text on a custom Django ModelChoiceField

2.4k Views Asked by At

I'm creating a custom ModelChoiceField so I can display custom labels for my foreign key, but in doing so Django no longer displays the help_text on the form. How can I get the help text back?

models.py

class Event(models.Model):

    title = models.CharField(max_length=120)
    category = models.ForeignKey(Category, default=Category.DEFAULT_CATEGORY_ID, on_delete=models.SET_NULL, null=True,
                                 help_text="By default, events are sorted by category in the events list.")

forms.py

class CategoryModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s (%s)" % (obj.name, obj.description)

class EventForm(forms.ModelForm):

    category = CategoryModelChoiceField(
        queryset=Category.objects.all(),
    )

    class Meta:
        model = Event
        fields = [...]
2

There are 2 best solutions below

0
On BEST ANSWER

With help from the comment below the question, here's how I got my custom form field to get the default help text back from the model:

class EventForm(forms.ModelForm):
    category = CategoryModelChoiceField(
        queryset=Category.objects.all(),
        help_text=Event._meta.get_field('category').help_text,
)
1
On

You can add it inside Meta.

from django.utils.translation import gettext_lazy as _

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

See django docs.

Also, you can add with __init__ method.

class EventForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs)
        self.fields['category'].help_text = ''