本文介绍了django-admin 中的动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让管理员添加表单动态化.我想根据相关对象中的设置添加一些表单域.
I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object.
我有这样的事情:
class ClassifiedsAdminForm(forms.ModelForm):
def __init__(self,*args, **kwargs):
super(ClassifiedsAdminForm, self).__init__(*args, **kwargs)
self.fields['testujemy'] = forms.CharField(label = "test")
在 admin.py 中:
And in admin.py:
class ClassifiedAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
return ClassifiedsAdminForm
如您所见,我想将testujemy"CharField 添加到管理员添加表单和更改表单.然而,这种方式行不通.有没有办法在 init 中添加字段?它在正常视图下工作.
As you can see, I want to add "testujemy" CharField to admin add-form and change-form. However, this way doesnt work. Is there any way to add field in init? It is working in normal view.
推荐答案
我已经设法使用 type() 做到了.
I've managed to do it using type().
class ClassifiedAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
adminform = ClassifiedsAdminForm()
fields = adminform.getNewFields()
form = type('ClassifiedsAdminForm', (forms.ModelForm,), fields)
return form
希望对某人有所帮助.
这篇关于django-admin 中的动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!