[Django]-ValueError: Cannot add *: instance is on database "default", value is on database "None"

83👍

The problem here is that you need to call the method save for both objects before adding the template to the product:

template.save()
plan.save()
plan.templates.add(template)

Django can’t add it if none of those objects has an id (plan and template)

3👍

One very common cause of this error is when you try to add the relations before saving the (parent) object. First, save the object and then add the relationships. Hopefully, it will be resolved.

Example:

a1 = Article(headline='Django lets you build Web apps easily')

Now, if you directly try to add the relations like this:

a1.publications.add(p1)

It will give an error.

Solution: SAVE IT first and then add relations!!

a1.save()
a1.publications.add(p1)

This will work flawlessly.

Docs

2👍

this will also happen if you override the save without calling the super().save(*args, **kwargs) if you added it to m2m even after you’re calling save

i.e:

# will raise a ValueError error 
def save(self, *args, **kwargs):
    # ..... somecode .....

def save(self, *args, **kwargs):
    # ..... somecode .....
    super().save(*args, **kwargs) # here
👤Fathy

Leave a comment