4

I'm going crazy today. I just tried to insert a new record and it threw back a "post_blogpost.id may not be NULL" error. Here's my model:

class BlogPost(models.Model):
    title   = models.CharField(max_length=100)
    slug    = models.SlugField(max_length=100)
    who     = models.ForeignKey(User, default=1)
    when    = models.DateTimeField()

    intro   = models.TextField(blank=True, null=True)
    content = models.TextField(blank=True, null=True)

    counter = models.PositiveIntegerField(default=0)

    published = models.BooleanField(default=False)
    css = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ('-when', 'id')

There are a number of functions beneath the model too but I won't include them in full here. Their names are: content_cache_key, clear_cache, __unicode__, reads, read, processed_content.

I'm adding through the admin... And I'm running out of hair.

Oli
  • 235,628
  • 64
  • 220
  • 299

2 Answers2

6

The only thing I can think of is that the table schema has become desynchronized from the model in that someone removed the AUTOINCREMENT attribute from the PK of the table.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • I've got to say, given that this is an error happening outside of my code it's entirely possible but how do I check if that's the case and how would I go about fixing it? – Oli Mar 29 '10 at 15:19
  • You would use your database tool to examine the properties of the table, and you would execute an `ALTER TABLE` query to re-add the constraint. See the relevant DB documentation for details. – Ignacio Vazquez-Abrams Mar 29 '10 at 15:21
  • I went with a somewhat riskier manage.py method: `dumpdata post > post.json`, `reset post`, `loaddata post.json`.. Still checking to make sure it hasn't nuked anything. – Oli Mar 29 '10 at 15:34
  • 1
    Took me 4 hours to track down the root of my problems. You're solution was spot on. Simply changed the SQLite field type to "INTEGER PRIMARY KEY" and it was fixed. – Kingpin Feb 24 '12 at 02:25
1

I've also experienced odd editing results in the admin. Usually they were related to foreign keys. When the edit page has a bunch of empty model instances on one page so that you can easily create new ones by filling them out, sometimes I managed to do something wrong such that an attempt would be made to save the empty instances. Maybe that applies for you.

You could verify that this adds fine by itself in a shell.

$ python manage.py shell
>>> from models import *
>>> b = BlogPost(title='Hello', slug='hello')
>>> b.save()
Alexander Ljungberg
  • 6,302
  • 4
  • 31
  • 37