django-admin 中的动态表单

Dynamic forms in django-admin(django-admin 中的动态表单)
本文介绍了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 中的动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)