gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:25 25 4
gpt4 key购买 nike

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"

关于python - 从不同的应用程序覆盖 Django 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11851267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com