当我的Django表单的clean()方法检测到错误时,我希望表单字段重新显示为空,而不是填写用户提供的任何输入。
我该怎么做?它是表单字段本身的属性,还是在clean()方法中完成的?我试过操纵self.cleaned_data ['fieldname'],但那不起作用。
谢谢!
答案 0 :(得分:2)
您需要在清洁方法中将字段的数据属性设置为'':
class MyForm(forms.Form):
name = forms.CharField(max_length=50)
def clean_name(self):
name = self.cleaned_data['name']
if name == 'Bob':
raise forms.ValidationError(u'Name cannot be "Bob"')
self.data['name'] = ''
return name
希望能帮到你。
[编辑]
这是一个在Django 1.3中为我工作的扩展示例。
#models.py
from django.db import models
class ContactRequest(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
subject = models.CharField(max_length=255)
message = models.TextField()
response_returned = models.BooleanField(default=False)
def __unicode__(self):
return self.name
#forms.py
class ContactRequestForm(forms.ModelForm):
class Meta:
model = ContactRequest
exclude = ('response_returned',)
def clean_email(self):
email = self.cleaned_data['email']
if email != 'test@test.com':
self.data['email'] = ''
raise forms.ValidationError(u'Email is not test@test.com')
return email
[编辑] 这是另一个示例,如果在clean方法中未满足条件,则清除所有字段。这在Django 1.1.4中适用于我。
#forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name')
email = cleaned_data.get('email')
if email == 'test@test.com' and name == 'test':
for k, _ in self.fields.iteritems():
self.data[k] = ''
raise forms.ValidationError(u'Email cannot be "test@test.com" and name cannot be "test"')
return cleaned_data