我在表单的 Meta 类中使用
exclude
从表单中排除我想以编程方式填写的字段,但它仍然显示在表单中。
以下是代码的一些摘录:
# Model
class Info(models.Model):
completed_by = models.ForeignKey(User, related_name='+')
# Form
class InfoForm(forms.ModelForm):
class Meta:
model = Info
exclude = ('created_by',) #ETA: added comma to make this a tuple
widgets = {
'some_other_field': forms.HiddenInput(),
'some_other_field2': forms.DateInput(attrs={'readonly': True}),
}
# View
form = InfoForm(initial={'some_other_field': value},
prefix='info', instance=info)
return direct_to_template(request, 'myapp/info.html', locals())
# Template
<form class='uniForm' method='POST'>
{% csrf_token %}
<fieldset class='inlineLabels'>{{ form|as_uni_form }}</fieldset>
<input type='submit' name='action' value='Save' />
</form>
这看起来应该很简单,而且我知道我以前已经成功完成过。 我已经删除/重新创建了数据库并清除了浏览器缓存,只是为了确保这不是一个因素。 我还尝试将其设为
HiddenInput
字段,就像 some_other_field
(这也是 ForeignKey
字段),但它仍然显示在表单上。
我有什么遗漏的吗? uni_form 是否以某种方式覆盖设置? 如果没有,关于我在调试中可能寻找什么来了解发生这种情况的位置/原因的任何建议?
(使用Django版本1.2.7)
排除需要一个元组,所以你需要
# note the extra comma
exclude = ['created_by',]
django 迭代
exclude
,并且由于字符串是可迭代的(返回每个字符),因此不会引发错误
对于较旧的 Django 版本,排除显式声明的非模型字段存在问题,例如在父窗体类中。在表单的 init 中添加以下内容甚至可以处理非模型字段(请参阅 https://code.djangoproject.com/ticket/8620)。
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
[self.fields.pop(f) for f in self.fields.keys() if f in self.Meta.exclude]
我知道这很旧,但在这里发布作为参考。
我遇到了同样的问题,因为我在模型上重载了
clean_fields()
,但没有正确调用超类。
class MyModel(models.Model):
foo = models.BooleanField()
# Wrong! Don't do this!
def clean_fields(self, exclude=None):
# Bah! Forgetting to pass exclude defaults it to None!
super(MyModel, self).clean_fields()
if not self.foo:
raise ValidationError('Ah fooey.')
# Correct! Do it this way!
def clean_fields(self, exclude=None):
# That's better! Let's take a coffee break. I'm tired.
super(MyModel, self).clean_fields(exclude)
if not self.foo:
raise ValidationError('Ah fooey.')