14

I'm attempting to display an image when editing a user on the admin panel, but I can't figure out how to add help text.

I'm using this Django Admin Show Image from Imagefield code, which works fine.

However the short_description attribute only names the image, and help_text doesn't seem to add an text below it.

How can I add help_text to this field like normal model fields?

EDIT:

I would like to have help_text on the image like the password field does in this screenshot:

screenshot of admin page

cdignam
  • 1,376
  • 1
  • 15
  • 21

3 Answers3

13

Use a custom form if you don't want change a model:

from django import forms

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['image'].help_text = 'My help text'

    class Meta:
        model = MyModel
        exclude = ()

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyForm
    # ...
Anton Shurashov
  • 1,820
  • 1
  • 26
  • 39
3

It took me a while to figure out. If you've defined a custom field in your admin.py only and the field is not in your model. Use a custom ModelForm:

class SomeModelForm(forms.ModelForm):
    # You don't need to define a custom form field or setup __init__()

    class Meta:
        model = SomeModel
        help_texts = {'avatar': "User's avatar Image"}
        exclude = ()

And in the admin.py:

class SomeModelAdmin(admin.ModelAdmin):
    form = SomeModelForm
    # ...
Community
  • 1
  • 1
Nitin Nain
  • 5,113
  • 1
  • 37
  • 51
  • 1
    Thank you! I didn't have to define `model` or `exclude` attributes either (just `help_texts`) to make it work with the Admin panel :D – Genarito Sep 14 '22 at 18:14
1

If you don't want to create a custom model form class :

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, change=False, **kwargs):
        form = super().get_form(request, obj=obj, change=change, **kwargs)
        form.base_fields["image"].help_text = "Some help text..."
        return form
WitoldW
  • 749
  • 10
  • 11