Django: I am getting "ValueError: needs to have a value for field "id" before this many-to-many relationship can be used."

I am trying to write a function record_post that saves a Post with the following model:

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    body = models.CharField(max_length=1000)
    date_created = models.DateTimeField()
    platforms = models.ManyToManyField(Platform)

And here is the record_post function:

def record_post(user, body=None, platforms=None):
    post = Post(
        user=user,
        body=body,
        date_created=timezone.now(),
    )

    # Add platforms
    facebook = Platform.objects.get(name="Facebook")

    if "facebook" in platforms:
        post.platforms.add(facebook)

    post.save()

    return post

However, when I run the function I get the following error: ValueError: "<Post: 53>" needs to have a value for field "id" before this many-to-many relationship can be used.

I managed to fix this by moving post.save() to after where the Post is initialized. So the full function now reads:

def record_post(user, body=None, platforms=None):
        post = Post(
            user=user,
            body=body,
            date_created=timezone.now(),
        )

        post.save() # MOVED LINE

        # Add platforms
        facebook = Platform.objects.get(name="Facebook")

        if "facebook" in platforms:
            post.platforms.add(facebook)

        return post
Back to Top