Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add placeholder text to a Django Admin field

Tags:

python

django

I'd like to add placeholder text to a field in the Django Admin change form. In a regular ModelForm you can do this by overriding the field's widget or by modifying self.fields['my_field'].widget in the ModelForm __init__() method. How do I do something similar for a Django Admin?

like image 209
Ben Sturmfels Avatar asked Dec 07 '25 08:12

Ben Sturmfels


1 Answers

The documented way is to override get_form():

The base implementation uses modelform_factory() to subclass form, modified by attributes such as fields and exclude.

If you look at the docs for modelform_factory you'll see that you can pass widgets as kwarg. So this should work:

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        kwargs['widgets'] = {
            'name': forms.TextInput(attrs={'placeholder': 'e.g. John Doe'})
        }
        return super().get_form(request, obj, **kwargs)

or, if you want to be sure you're not overriding any widgets (if you're inheriting from a subclass of ModelAdmin):

 kwargs['widgets'] = kwargs.get('widgets', {})
 kwargs['widgets'].update({'name': ...})
like image 166
dirkgroten Avatar answered Dec 08 '25 21:12

dirkgroten