我使用Django表单来控制content.The函数的长度,但是错误信息包含一些我不需要的额外单词和标点符号。
我的问题是如何删除额外的单词和标点符号?
这是我的表格:
def words_validator(comment):
if len(comment) < 4:
raise ValidationError("您输入的评论字数太短,请重新输入至少4个字符")
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator])这是我的模板:
{% if comment_form.errors %}
<div class="ui error" >
{{comment_form.errors}}
</div>
{% endif %}错误信息在这里:
·comment
。您输入的评论字数太短,请重新输入至少4个字符我只需要‘您输入的评论字数太短,请重新输入至少4个字符’,不需要标点符号和字段名‘注释’。
有朋友有解决办法吗?
发布于 2018-04-24 18:38:51
你需要遍历表单,然后是field.errors,
喜欢,
{% for field in form %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
{% endfor %}示例:
myapp.forms.py
def words_validator(comment):
if len(comment) < 4:
raise ValidationError("Lenght should be greater than 4")
class Demo(forms.Form):
comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator])壳牌:
In [1]: html = """
...: {% for field in form %}
...: {% for error in field.errors %}
...: {{ error }}
...: {% endfor %}
...: {% endfor %}
...:
...: """
In [2]: from django.template import Context, Template
In [3]: from myapp.forms import *
In [4]: form = Demo({'comment': 'abc'})
In [5]: t = Template(html)
In [6]: c = Context({'form': form})
In [7]: print t.render(c)
Lenght should be greater than 4https://stackoverflow.com/questions/50008291
复制相似问题