开发者

Django model accepts blank values for field defined as NOT NULL

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 li开发者_JS百科ne (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?


A few questions

  1. What version of django are you using?
  2. What database are you using?
  3. If you look at your database record after you save via the shell what is in the database for create_date?
  4. If you look at the schema definition for the table in the database does it allow nulls for create_date? Is there a default set?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜