我添加了一個自定義字段到的ModelForm在管理使用:如何從管理員動態排除非模型字段?
class MyModel(models.Model):
name = models.CharField(max_length=64)
...etc...
class MyModelAdminForm(forms.ModelForm):
dynamicfield = forms.IntegerField()
def __init__(self, *args, **kwargs):
super(MyModelAdminForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
#remove dynamicfield from the form, somehow?
def save(self, *args, **kwargs):
#do something with dynamicfield
super(MyModelAdminForm, self).save(*args, **kwargs)
class Meta:
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
admin.site.register(MyModel, MyModelAdmin)
這一領域的重點是收集初始對象創建過程中需要更多的數據。因此,它應該只在創建新對象時出現(檢查「實例」)。
我遇到的問題是在編輯現有對象時使字段消失。我試過了:
self.fields['dynamicfield'].widget = self.fields['dynamicfield'].hidden_widget()
但是,只有擺脫了文本輸入字段,而不是標籤。
我還試圖對這些變化(也使用base_fields到位領域的super()
調用之前):
del self.fields['dynamicfield'] #yields error:
TemplateSyntaxError at /admin/db/myapp/mymodel/6/
Caught an exception while rendering: Key 'dynamicfield' not found in Form
self.fields['dynamicfield'].hidden = True #Does nothing.
self.fields['dynamicfield'] = None #yields error:
TemplateSyntaxError at /admin/db/catalog/product/6/
Caught an exception while rendering: 'NoneType' object has no attribute 'label'
之前做這些)調用超(也嘗試過,但也失敗:
del self.base_fields['dynamicfield'] #yields error:
TemplateSyntaxError at /admin/db/myapp/mymodel/6/
Caught an exception while rendering: Key 'dynamicfield' not found in Form
已經嘗試過那個。與del self.fields ['dynamicfield'](上面)完全相同的錯誤。 – Sam 2010-02-01 21:32:13