Homunculus Reticulli
Homunculus Reticulli

Reputation: 68456

Django models create() and save() not persisting in database (pk / id attribute on instance is not set)

I am using Django 2.2

This is my model

models.py

class WebPage(models.Model):
    breadcrumb = models.CharField(blank=False, null=False, max_length=128, unique=True)
    slug = models.SlugField(blank=False, null=False, max_length=128, unique=True)
    content = RichTextField()
    creator = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
    is_published =  models.BooleanField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.breadcrumb
    
    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.breadcrumb)

I am using sqlite as the backend db. Here is my settings file (relevant section)

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

./manage.py shell

>>> wp=WebPage.objects.create(breadcrumb='hello/there', content='<span></span>')
>>> wp.id
>>> wp.save()
>>> wp.id
>>> wp.slug
'hellothere'
>>> wp.save(persist=True)
>>> wp.id
>>> 

Why is the object not being saved to the database - and how do I fix this?

Upvotes: 0

Views: 430

Answers (1)

JPG
JPG

Reputation: 88549

You have missed calling the super() method, which is actually creating the instances in Database.

class WebPage(models.Model):
    # rest of your code

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.breadcrumb)

        super().save(*args, **kwargs)

Upvotes: 2

Related Questions