1

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 = [...]
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94
  • Pass in the `help_text` as an argument to `CategoryModelChoiceField`. Maybe you can access it like `help_text=self._meta.model.category.help_text` or something similar. – dan-klasson May 23 '18 at 22:24

2 Answers2

2

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,
)
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94
1

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 = ''
cdosborn
  • 3,111
  • 29
  • 30
seuling
  • 2,850
  • 1
  • 13
  • 22