我正在尝试使用以下代码将自定义字段添加到InlineFormset,但这些字段不会显示在Django Admin中。 InlineFormset是否也被锁定以允许此操作?我的打印“ding”测试按预期触发,我可以打印出form.fields并在那里看到它们,但实际的字段永远不会在管理员中呈现。
admin.py
from django.contrib import admin
import models
from django.forms.models import BaseInlineFormSet
from django import forms
from forms import ProgressForm
from django.template.defaultfilters import slugify
class ProgressInlineFormset(BaseInlineFormSet):
def add_fields(self, form, index):
print "ding"
super(ProgressInlineFormset, self).add_fields(form, index)
for criterion in models.Criterion.objects.all():
form.fields[slugify(criterion.name)] = forms.IntegerField(label=criterion.name)
class ProgressInline(admin.TabularInline):
model = models.Progress
extra = 8
formset = ProgressInlineFormset
class ReportAdmin(admin.ModelAdmin):
list_display = ("name", "pdf_column",)
search_fields = ["name",]
inlines = (ProgressInline,)
admin.site.register(models.Report, ReportAdmin)
答案 0 :(得分:4)
我是用另一种方式做的:
forms.py:
from django import forms
class ItemAddForm(forms.ModelForm):
my_new_field = forms.IntegerField(initial=1, label='quantity')
class Meta:
model = Item
admin.py:
from django.contrib import admin
from forms import *
class ItemAddInline(admin.TabularInline):
form = ItemAddForm
到目前为止,我只需要以某种方式覆盖save方法来处理这个新字段。见:http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form。它表示默认情况下Inlines使用BaseModelForm,它发送到formset_factory。它对我不起作用,试图将BaseModelForm子类化为错误(没有属性'_meta')。所以我改用ModelForm。
答案 1 :(得分:2)
您可以通过其他方式(动态表单)执行此操作:
<强> admin.py 强>
class ProgressInline(admin.TabularInline):
model = models.Progress
extra = 8
def get_formset(self, request, obj=None, **kwargs):
extra_fields = {'my_field': forms.CharField()}
kwargs['form'] = type('ProgressForm', (forms.ModelForm,), extra_fields)
return super(ProgressInline, self).get_formset(request, obj, **kwargs)
答案 2 :(得分:1)