Search code examples
djangoabstract-class

Django - Add help text to field inherited from abstract base class


I just discovered the "help_text" attribute at Django model fields which automatically adds help textes to fields e.g. in the admin panel. Again, what a nice Django feature!

Now I have the problem that I want to add the help_text to a field which is inherited from a parent abstract base class... how could I achieve this?

class AbstractBioSequence(models.Model):
"""
General sequence (DNA or AA)
"""
    name_id = models.CharField(max_length=100, null=True)
    description = models.CharField(max_length=1000, null=True, blank=True)
    sequence = models.TextField()

    class Meta:
        abstract = True

class DnaSequence(AbstractBioSequence):
    some_dna_field = models.TextField()
    # -------- I want to add a DnaSequence specific helper text to the "sequence" field here

Solution

  • The many ways to do it exists.

    Django documentation way:

    class DnaSequence(AbstractBioSequence):
        some_dna_field = models.TextField()
        description = models.CharField(max_length=1000, null=True, blank=True, help_text=_("DnaSequence specific helper text"))
    

    don't forget to makemigrations, your help_text should be added to migration schema.

    Monkey-Patcher way:

    class DnaSequence(AbstractBioSequence):
        some_dna_field = models.TextField()
    
    DnaSequence._meta.get_field('description').help_text = _("DnaSequence specific helper text")
    

    In earlier version it was get_field_by_name method. More about it: https://docs.djangoproject.com/en/4.1/ref/models/meta/#django.db.models.options.Options.get_field

    In this art of changes you shouldn't get any migration.

    Other ideas:

    1. You can override form field help text. It works good for ModelAdminForm. More here: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#overriding-the-default-fields
    2. You can create you own help_text_model, and add help_text on-fly to field with Mixin.
    3. Many other ways...