How to override help_text in django admin interface

I have several admin sites, so different users get different experiences editing objects in the database. Each admin site has a different set of objects and a different style. All of this can be done by overriding the ModelAdmin templates and objects.

I cannot decide how to provide different help_text across different sites. help_text is always taken directly from the model field definition, and there seems to be no way to override it.

Am I missing something, or is it impossible?

+6
source share
5 answers

You can create a new model and override help_text:

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

then use the new form in ModelAdmin:

 class MyModel(admin.ModelAdmin): ... form = MyForm 

This is a cleaner way to achieve what you want, since form fields belong to forms anyway!

+12
source

In Django 1.9, as shown below, works for me

 def get_form(self, request, obj=None, **kwargs): form = super(MyAdmin, self).get_form(request, obj, **kwargs) form.base_fields['my_field'].help_text = """ Some helpful text """ return form 
+4
source

Kerin is right, but his code does not work (at least with Django 1.4).

 def get_readonly_fields(self, request, obj): try: field = [f for f in obj._meta.fields if f.name == 'author'] if len(field) > 0: field = field[0] field.help_text = 'some special help text' except: pass return self.readonly_fields 

You will need to change the line "author" and help_text to suit your needs.

+1
source

You can always change the attributes of a form field in the ModelAdmin constructor, for example:

  def __init __ (self, * args, ** kwargs):
         super (ClassName, self) .__ init __ (* args, ** kwargs)
         if siteA:
             help_text = "foo"
         else:
             help_text = "bar"
         self.form.fields ["field_name"]. help_text = help_text
0
source

Try this (you may need to replace self.fields with self.form.fields ...)

 class PropertyForm(models.ModelAdmin): class Meta: model = Property def __init__(self, *args, **kwargs): super(PropertyForm, self).__init__(*args, **kwargs) for (key, val) in self.fields.iteritems(): self.fields[key].help_text = 'what_u_want' 
-1
source

Source: https://habr.com/ru/post/886319/


All Articles