我有一个Django模型和表单,定义如下:
class LabelModel(models.Model):
image = models.FileField(upload_to='documents/label',
db_column='path', default='Some Value')
相应的表格如下:
class DocumentForm(forms.Form):
labelled_image = forms.FileField(label='Select the Label image')
我有一个简单的验证方法,用于检查文件扩展名。
def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.split(value.name)[1] # [0] returns path+filename
valid_extensions = ['.img']
if not ext.lower() in valid_extensions:
return False
return True
现在,在POST方法中,我执行以下操作:
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
labelled_file = request.FILES['labelled_image']
has_errors = validate_file_extension(labelled_file)
现在,如果我有错误,我想更新渲染页面并显示错误消息:
因此,我的模板呈现代码如下:
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.labelled_image.label_tag }} {{ form.labelled_image }} {{ form.labelled_image.errors }} </p>
<p><input type="submit" value="Upload"/></p>
</form>
现在,我不知道如何使用我自己的错误消息更新此{{ form.labelled_image.errors }}
,以便它可以显示给用户。
答案 0 :(得分:1)
以下是填充errors
值的方法:
class DocumentForm(forms.Form):
labelled_image = forms.FileField(label='Select the Label image')
def clean_labelled_image(self):
# ... (your validation code here) ...
raise forms.ValidationError('Custom error message here')
通过将验证置于clean_<name>
函数中,您可以提出ValidationError
{{form.labelled_image.errors}}
,form.is_valid()
运行www.../carnival - index page that displays all child objects
www.../carnival/rides-games - child page of carnival
www.../carnival/etc...
。