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

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

问题描述

我有一个看起来像这样的简单模型:

class Group(models.Model):名称 = 模型.CharField(max_length = 100, 空白=假)

我希望这会引发完整性错误,但它不会:

group = Group() # 此处名称为空字符串组.save()

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

解决方案

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

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

在此页面上,您可以看到 blank 与数据库无关.

更新:

您应该覆盖模型的干净功能,以进行自定义验证,因此您的模型定义将是:

class Group(models.Model):name = models.CharField(max_length=100, blank=False)def清洁(自我):从 django.core.exceptions 导入验证错误如果 self.name == '':raise ValidationError('空错误信息')

或者您可以将 ValidationError 替换为其他内容.然后在你调用 group.save() 之前调用 group.full_clean() 它将调用 clean()

其他与验证相关的内容在这里.>

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?

解决方案

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.

Update:

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')

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

Other validation related things are here.

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

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