Django 模型接受定义为 NOT NULL 的字段的空白值
编辑:3-4 周后我再次尝试此操作,但没有再次遇到此问题。我不知道为什么。当我第一次遇到这个问题时,我很惊讶 Django 没有抛出任何 NOT NULL 约束。但现在,当我 3-4 周后再次尝试时,效果很好。我不知道为什么。
无论如何,这个问题不再有效。
我是 Django 新手。
我的模型有一个类,它有几个定义为 NOT NULL 的字段。
class Post(models.Model):
title = models.CharField(max_length=60)
create_date=models.DateField(verbose_name='created Date')
当我进入命令行(通过manage.py shell)并通过执行以下操作创建一个新的 Post 实例时,Django 会将条目保存到数据库中:
p=Post(title='test')
p.save()
为什么它不会像我尝试与管理面板相同吗?
EDIT: I tried this out again after 3-4 weeks and I did not encounter this problem again. I'm not sure why. I was quite surprised that Django wasn't throwing up any NOT NULL constraint when I first encountered this problem. But now, when I tried it again after 3-4 weeks, it works fine. I'm not sure why.
Anyway, this question is not really valid any more.
I'm a Django newbie.
My model has a class that has a couple of fields which are defined as NOT NULL.
class Post(models.Model):
title = models.CharField(max_length=60)
create_date=models.DateField(verbose_name='created Date')
When I go to the command line (through manage.py shell), and create a new Post instance by doing the following, Django saves the entry to the database:
p=Post(title='test')
p.save()
Why doesn't it throw up an error like it does when I attempt the same from the Admin panel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几个问题
我还没有机会尝试这段代码,但这是我对正在发生的事情的猜测。
django 管理员正在使用表单验证来阻止您保存,并给您错误。
当您使用 shell 时,模型没有验证,因此它允许您保存,并且它依赖数据库来捕获可为空数据的问题。我的猜测是您的数据库允许该值为空并且不会引发错误,因此它允许您毫无问题地保存。
在 Django 1.2 中,他们添加了与表单验证器类似的模型验证器,请查看此链接以获取更多信息。
http://docs.djangoproject.com/en/1.2/ ref/models/instances/#validating-objects
再次,我只是在这里猜测,因为我不知道上述问题的答案。如果您能给我这些答案,我应该能够给您更好的答案。
A few questions
I haven't had a chance to try this code out yet, but this is my guess as to what is going on.
The django admin is using form validation to stop you from saving, and giving you the error.
When you use the shell the model doesn't have validation, so it is allowing you to save, and it is relying on the database to catch the issues with the nullable data. My guess is that your database is allowing this value to be null and isn't throwing an error and thus it allows you to save with no issues.
In Django 1.2 they added model validators that are similar to form validators, check out this link for more info.
http://docs.djangoproject.com/en/1.2/ref/models/instances/#validating-objects
Once again, I'm just taking a guess here since I don't know the answers to the questions above. If you could get me those answers I should be able to give you a better answer.