我有一个简单的ModelForm:
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
del self.fields['name']
正如您所看到的,我尝试从表单的字段列表中删除一个字段(该字段明确存在于模型中),但我得到一个异常:
TemplateSyntaxError at [..]
Caught an exception while rendering: "Key 'name' not found in Form"
我没有编写自定义表单,因此发生错误的模板是:
/templates/admin/includes/fieldset.html, error at line 4
有什么想法吗?
- 更新 -
问题仅出现在管理区域中。
- 更新2 -
也许跟踪转储提供了更多信息:
Original Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/template/debug.py", line 71, in render_node
result = node.render(context)
File "/Library/Python/2.5/site-packages/django/template/defaulttags.py", line 155, in render
nodelist.append(node.render(context))
File "/Library/Python/2.5/site-packages/django/template/defaulttags.py", line 239, in render
value = bool_expr.resolve(context, True)
File "/Library/Python/2.5/site-packages/django/template/__init__.py", line 546, in resolve
obj = self.var.resolve(context)
File "/Library/Python/2.5/site-packages/django/template/__init__.py", line 687, in resolve
value = self._resolve_lookup(context)
File "/Library/Python/2.5/site-packages/django/template/__init__.py", line 722, in _resolve_lookup
current = current()
File "/Library/Python/2.5/site-packages/django/contrib/admin/helpers.py", line 81, in errors
return mark_safe(u'\n'.join([self.form[f].errors.as_ul() for f in self.fields]).strip('\n'))
File "/Library/Python/2.5/site-packages/django/forms/forms.py", line 105, in __getitem__
raise KeyError('Key %r not found in Form' % name)
KeyError: "Key 'name' not found in Form"
在管理区域,我使用Grapelli-Theme。也许这与问题有关?
答案 0 :(得分:13)
我遇到了同样的问题。这就是我在新的Django(trunk)中使用它的方法:
class MyModelAdmin(admin.ModelAdmin):
# Your stuff here..
def get_form(self, request, obj=None, **kwargs):
if request.user.is_staff: # condition
self.exclude = ('field',)
return super(PublishAdmin, self).get_form(request, obj=obj, **kwargs)
通过覆盖get_form
方法并将逻辑放在此处,您可以选择要显示的Form
。上面我已经满足条件时显示标准表格。
答案 1 :(得分:6)
如Creating forms from models - Selecting the fields to use所述,有三种方式:
editable=False
。从模型创建的所有表单都将排除该字段。fields
内部类中定义Meta
属性,仅包含您想要的字段。exclude
内部类中定义Meta
属性,列出您不想要的字段。因此,如果您的模型包含字段field1
,field2
和field3
,并且您不想要field3
,那么#2技术将如下所示:
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('field1', 'field2')
技术#3看起来像这样:
class MyModelForm(ModelForm):
class Meta:
model = MyModel
exclude = ('field3',)
答案 2 :(得分:3)
这很有效......
def __init__(self, instance, *args, **kwargs):
super(FormClass, self).__init__(instance=instance, *args, **kwargs)
if instance and instance.item:
del self.fields['field_for_item']
答案 3 :(得分:1)
我能想到的一个原因是,使用自定义表单的ModelAdmin类是否存在冲突设置。例如,如果您还在ModelAdmin的“字段”或“字段集”中明确指定了“名称”字段。
答案 4 :(得分:0)
您可以使用exclude属性从ModelForm中删除字段
exclude = ('field_name1', 'field_name2,)