你如何在Django中创建一个非空CharField? [英] How can you create a non-empty CharField in Django?

查看:577
本文介绍了你如何在Django中创建一个非空CharField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型,如下所示:

I have a simple model which looks like this:

class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)

我希望这会抛出一个完整性错误,但它不:

I would expect this to throw an integrity error, but it does not:

group = Group() # name is an empty string here
group.save()

如何确保名称变量设置为非空?即使数据库拒绝任何保存空字符串的尝试?

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

推荐答案

Django docs 在这种情况下,您的名称将存储为空字符串,因为默认情况下 null 字段选项为False。如果要定义自定义默认值,请使用默认值字段选项。

From the Django docs in this case, your name will be stored as an empty string, because the null field option is False by default. if you want to define a custom default value, use the default field option.

name = models.CharField(max_length=100, blank=False, default='somevalue')

在此页面上,您可以看到空白不是数据库 -

On this page, you can see that the blank is not database-related.

更新:

您应该覆盖模型的干净功能,要自定义验证,所以你的模型def将是:

You should override the clean function of your model, to have custom validation, so your model def will be:

class Group(models.Model):
  name = models.CharField(max_length=100, blank=False)
  def clean(self):
    from django.core.exceptions import ValidationError
    if self.name == '':
        raise ValidationError('Empty error message')

或者您可以替换 ValidationError 到别的东西。然后在调用 group.save()调用 group.full_clean()之前调用 clean()

Or you can replace ValidationError to something else. Then before you call group.save() call group.full_clean() which will call clean()

其他验证相关的内容是 here

Other validation related things are here.

这篇关于你如何在Django中创建一个非空CharField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆