form无法自定错误信息

2013-10-16 11:18:03 +08:00
 halicando
用了def clean_somefield()方法;

也用了这个方法 http://www.oschina.net/question/247206_45024 ;

也尝试修改了django\conf\locale\zh_CN\LC_MESSAGES\django.po下的本地化内容都没用。
2533 次点击
所在节点    Python
2 条回复
jokaye
2013-10-16 14:32:27 +08:00
class YourForm(ModelForm):

def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.error_message = 'whatever you want'

def clean_somefield(slef):
if not check_somefield_valid(): //do your check in here
raise formValidateError(self.error_message)
return self
halicando
2013-10-17 20:16:31 +08:00
@jokaye

好像还是不行

版本信息:django1.3.1 ,python2.7.1

以下是代码:

class TopicForm(forms.Form):

title=forms.CharField(max_length=50,label='标题')
content=forms.CharField(max_length=300,widget=forms.Textarea(),label='内容')

def __init__(self, *args, **kwargs):
super(TopicForm, self).__init__(*args, **kwargs)
self.error_message = u'不超过300字'

def clean_title(self):
title = self.cleaned_data['title']
if len(title) > 50:
raise forms.ValidationError(u'不超过50字')
return title

def clean_content(self):
content = self.cleaned_data['content']
if len(content) > 300:
raise forms.ValidationError(self.error_message)
return content

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/85738

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX