pythondjangomodelformmodelchoicefield

How to get help_text on a custom Django ModelChoiceField


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 = [...]

Solution

  • 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,
    )