将动态字段添加到Django管理模型表单 [英] Add dynamic field to django admin model form
问题描述
我需要将带有指向我网站上的模型视图链接的字段添加到django管理员视图。
当我将字段名称添加到 list_display
并定义呈现此URL的方法时:
I need to add the field with link to the model view on my site to the django admin view.
When I add field name to the list_display
and define method for rendering this url:
class SetAdmin(admin.ModelAdmin):
list_display = ['many other fields', 'show_set_url']
def show_set_url(self, obj):
return '<a href="#">Set</a>' # render depends on other fields
它在django admin的集合列表中显示,但不以模型形式显示。
如何解决此问题并在django admin中添加到Sets Form的链接?
It shows in Sets list in django admin, but not in model form. How can I fix this and add link to the Sets Form in django admin?
我也尝试为此模型创建自定义表单:
I've tried also to create custom form for this model:
from core.models import Set
from django import forms
class SetAdminForm(forms.Form):
class Meta:
model = Set
def __init__(self, *args, **kwargs):
super(SetAdminForm, self).__init__(*args, **kwargs)
self.fields['foo'] = forms.IntegerField(label=u"Link")
但是现在有可见的形式。
But there is now visible effect in form.
推荐答案
您可以完成自己的工作请通过重写 ModelAdmin
进行尝试,但您还需要重写 ModelAdmin.get_fieldsets
。 此答案可能会帮助您。链接中的OP也有类似的问题。
You can accomplish what you're trying by overriding ModelAdmin
but you also need to override ModelAdmin.get_fieldsets
. This answer might help you out. The OP in the link has a similar problem as well.
编辑::如果您不希望使用可编辑字段,可以尝试覆盖 ModelAdmin.get_readonly_fields
。还要在此处中进行检查,以覆盖更多要覆盖的属性。
If you don't want an editable field you can try overriding ModelAdmin.get_readonly_fields
. Also check here for more attributes to override.
这篇关于将动态字段添加到Django管理模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!