Django 1.5基于类的视图,包含来自模型的自定义验证消息

时间:2022-10-30 19:21:38

I'm writing a fairly simple bit of CRUD in my django application for project management. I've got the following set up (leaving out the various imports etc for brevity):

我在django项目管理应用程序中编写了一个相当简单的CRUD。我有以下设置(为了简洁省略了各种进口等):

#models.py:
class Project(models.Model):
    name = models.CharField('Name', max_length=250, error_messages={'required': 'Please enter a name for your project.'})
    description = models.TextField()

#views.py
class ProjectUpdateView(UpdateView):
    model = Project

#templates/projects/project_form.html
<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" />
</form>

When I visit my update page, the form is displayed with my two fields (name and description). If I leave out the name then submitting the form brings back an error of

当我访问我的更新页面时,表单显示我的两个字段(名称和描述)。如果我省略了名称,那么提交表单会带来错误

This field is required

rather than

Please enter a name for your project.

Can I get my custom error message as defined in the model to display instead of the generic "This field is required"?

我是否可以获取模型中定义的自定义错误消息而不是通用的“此字段是否必需”?

1 个解决方案

#1


1  

Here's a Django ticket regarding the issue you're having: https://code.djangoproject.com/ticket/13693

这是关于你遇到的问题的Django门票:https://code.djangoproject.com/ticket/13693

Looks like it's been accepted but hasn't been fixed yet. Your best bet for now is to explicitly handle the validation in your form class.

看起来它已被接受但尚未修复。您现在最好的选择是明确处理表单类中的验证。

#1


1  

Here's a Django ticket regarding the issue you're having: https://code.djangoproject.com/ticket/13693

这是关于你遇到的问题的Django门票:https://code.djangoproject.com/ticket/13693

Looks like it's been accepted but hasn't been fixed yet. Your best bet for now is to explicitly handle the validation in your form class.

看起来它已被接受但尚未修复。您现在最好的选择是明确处理表单类中的验证。