Skip to main content
 首页 » 编程设计

python之从不同的应用程序覆盖 Django 表单字段

2025年05月04日22yxwkf

Django Guardian 在 admin.py 中定义了两种形式,GroupManage 和 UserManage:https://github.com/lukaszb/django-guardian/blob/master/guardian/admin.py#L368

我想为这两种形式添加自动完成,我认为实现这一目标的最佳方法是覆盖组和用户的字段小部件(我的第一次尝试使用 django autocomplete_light。)目标是不需要 fork django 监护人。

所以在我的应用程序的 models.py 中,我添加了以下代码

GroupManage.__class__.group = forms.CharField(max_length=81, 
    error_messages={'does_not_exist': 
    "This group does not exist!"}, widget=ChoiceWidget(True)) 

我也尝试过使用 setattr 无济于事。在 django shell 中,它的行为应该是这样的,但是当加载管理页面时,旧的组变量被恢复,使用默认的 CharField 小部件。

请您参考如下方法:

为类定义的字段存储在字典 base_fields 中。

GroupManage.base_fields['group'] = forms.CharField(max_length=81, 
error_messages={'does_not_exist': 
"This group does not exist!"}, widget=ChoiceWidget(True)) 

有时,更改字段属性而不是替换整个字段可能更容易:

GroupManage.base_fields['group'].help_text = "New help text"