将自定义错误消息添加到ModelForm字段

时间:2010-09-07 23:16:31

标签: django django-models django-forms

有没有办法将自定义错误消息添加到模型字段而不在表单中将其声明为表单字段?这可能吗?

我不想再次声明该字段,例如

class MyModel(models.Model):
    test = models.URLField(max_length = 200)

class MyForm(forms.ModelForm):
    test = forms.URLField(max_length = 200, error_messages={'required' : 'Custom error message'})
    class Meta:
        model = models.test

有没有办法提供自定义错误消息而不在表单中再次定义?

已修改模型

class MyModel(models.Model):
    link = models.URLField(verify_exists = False, max_length = 225, error_messages={'required' : 'Link cannot be left blank.'})

修改

我应该澄清一下,我的模型也有一个模型表格。这是实际的代码

class Story(models.Model):
    title = models.CharField(max_length = 225, error_messages={'required' : 'cannot be left blank'})
    link = models.URLField(verify_exists = False, max_length = 225, error_messages={'required' : ugettext_lazy(u"Link cannot be left blank.") })

形式

class StoryForm(forms.ModelForm):

    class Meta:
        model = models.Story
        fields = ('title', 'link')

    def clean_link(self):
        link = self.cleaned_data['link']
        return link.strip()

    def clean_title(self):
        title = self.cleaned_data['title']
        return title.strip()

我不想在我的表单中声明字段,因为我遇到了这里讨论的这个问题

Cleaning data which is of type URLField

1 个答案:

答案 0 :(得分:0)