本文介绍了django-admin中的动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让管理员添加表单动态。我想添加几个表单域,具体取决于相关对象中的设置。我有这样的东西:
class ClassifiedsAdminForm(forms.ModelForm):
def __init __(self,* args,** kwargs):
super(ClassifiedsAdminForm,self ).__ init __(* args,** kwargs)
self.fields ['testujemy'] = forms.CharField(label =test)
在admin.py:
class ClassifiedAdmin(admin.ModelAdmin) :
def get_form(self,request,obj = None,** kwargs):
return ClassifiedsAdminForm
如您所见,我想将testujemyCharField添加到admin add-form和change-form中。但是,这种方式不行。有没有办法在 init 中添加字段?
解决方案
我已经设法使用type()。
class ClassifiedAdmin(admin.ModelAdmin):
def get_form(self,request,obj = None,** kwargs):
adminform = ClassifiedsAdminForm()
fields = adminform.getNewFields()
form = type('ClassifiedsAdminForm',(forms.ModelForm,),fields)
返回表单
希望会帮助某人。
I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object.
I have something like this:
class ClassifiedsAdminForm(forms.ModelForm):
def __init__(self,*args, **kwargs):
super(ClassifiedsAdminForm, self).__init__(*args, **kwargs)
self.fields['testujemy'] = forms.CharField(label = "test")
And in admin.py:
class ClassifiedAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
return ClassifiedsAdminForm
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.
解决方案
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
Hope it will help someone.
这篇关于django-admin中的动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!