在 Django 管理中,如何将博客文章设置为仅验证它是否是草稿?
我正在为 Django 开发一个博客,我想使用 Django 管理员的内置验证。但是,如果博客文章状态设置为“草稿”,我想要某种方法来禁用验证。
基本上,我正在寻找应该执行以下操作的代码:
def validate(self, **kwargs):
''' do not validate drafts '''
if self.status != Post.STATUS_DRAFT:
Super(Post, self).validate(**kwargs)
I'm working on a blog for Django, and I would like to use the Django admin's built in validation. However, I would like some way to disable validation if the blog post status is set to "draft".
Basically, I'm looking for code that should do something like this:
def validate(self, **kwargs):
''' do not validate drafts '''
if self.status != Post.STATUS_DRAFT:
Super(Post, self).validate(**kwargs)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能不验证表单。例如,表单验证的作用是确保应包含数字的值包含数字。您认为帖子处于“草稿”模式这一事实并不能成为日期字段必须包含日期而不是无意义文本字符串的借口。
我想您想要的是允许某些字段在正常模式下是必需的,但在草稿模式下是可选的。
在这种情况下,这是在模型级别完成的。您可以使用自定义管理表单来强制执行此行为:
You can't not validate forms. The role of form validation is to make sure that, for example, a value that should contain a number contains a number. The fact that you believe the post to be in "draft" mode does not excuse the necessity of a date field to contain a date rather than a string of meaningless text.
I imagine what you want is to allow certain fields to be required in normal mode, but optional in draft mode.
In which case, this is done on the model level. You can use a custom admin form to enforce this behavior: