add help text to a read only field in django admin view

僤鯓⒐⒋嵵緔 提交于 2019-12-10 21:07:14

问题


Below is my admin view:

@admin.register(AuditStashAwsMasterPolicies)
class AuditPoliciesAdmin(reversion.VersionAdmin):
exclude = ['source_policy_path', 'source_state', 'target_state']
readonly_fields = ['comparison_date', 'source', 'source_policy_name', 'target', 'target_policy_name',
                   'target_policy_path', 'policy_difference']

def policy_difference(self, instance):
    return drift.compare_two_policies(instance.source, instance.source_policy_name, instance.source_policy_path,
                                instance.target, instance.target_policy_name, instance.target_policy_path)

What I want to do is add some help text to my 'policy_difference' read only field. From the help documentation, I am only able to do this by modifying the model and creating a read-only field there with help text.

The thing is I don't store any values in the 'policy_difference' field I just generate it on the fly and would like to avoid storing it in the model.

Is there any way to add text to the 'policy_difference' read-only field without changing the model AuditStashAwsMasterPolicies?


回答1:


You can achieve it by overriding the get_form method like so:

def get_form(self, request, obj=None, **kwargs):
    help_texts = {'policy_difference': 'Help text explaining policy difference'}
    kwargs.update({'help_texts': help_texts})
    return super(AuditPoliciesAdmin, self).get_form(request, obj, **kwargs)

The help_texts keyword gets eventually passed to the modelform_factory method and rendered as the standard help text from a model in the Django admin.

In case you're using an InlineModelAdmin, you need to override get_formset in the same manner.



来源:https://stackoverflow.com/questions/40878081/add-help-text-to-a-read-only-field-in-django-admin-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!