从ModelForm中删除字段 [英] Remove fields from ModelForm
问题描述
我有一个简单的ModelForm:
i have a simple ModelForm:
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
del self.fields['name']
如您所见,我尝试从表单的字段列表中删除一个字段(该模型中确切存在的字段),但是得到一个例外:
As you can see, I try to remove a field from the form's field list (the field definitively exists in the model), but I get an Exception:
TemplateSyntaxError at [..]
Caught an exception while rendering: "Key 'name' not found in Form"
我没有写一个自定义表单,所以模板中发生错误是:
I did not write a custom form, so the template where the error occurs is:
/templates/admin/includes/fieldset.html, error at line 4
任何想法?
- 更新 -
问题只出现在管理区域。
The problem appears only in the admin area.
- 更新2 -
-- UPDATE 2 --
也许跟踪转储提供更多信息:
Maybe a trace dump gives more info:
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主题。也许这与问题有关?
In the admin area, I use the Grapelli-Theme. Maybe this has to do with the problem?
推荐答案
我也有同样的问题。这就是我在新的Django(主干)中的工作原理:
I had the same problem. This is how I made it work in the new 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
你想要显示。以上我在符合条件时显示了标准表格。
By overriding the get_form
method and putting the logic here you can select which Form
you want to have displayed. Above I have displayed the standard form when a condition was met.
这篇关于从ModelForm中删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!