Nader
Nader

Reputation: 77

IntegrityError at /posts/create/18/: Key (group_id)=(18) is not present in table "auth_group"

getting this error when running the following code when trying to create a post, which belongs to a group and a user:

from django.shortcuts import render, get_object_or_404
from groups.models import Group
from .models import Post
from django.utils import timezone


def create(request, group_id):
    group = get_object_or_404(Group, pk= group_id)
    if request.method == 'POST':
        if request.POST['body'] and request.POST['body']:
            post = Post()
            post.title = request.POST['title']
            post.body = request.POST['body']
            post.pub_date = timezone.datetime.now()
            post.author = request.user
            post.group = group
            post.save()
            return redirect('/groups/' + str(group_id))

        else:
            return render(request, 'groups/detail.html', {'group':group})

    else:
        return render(request, 'groups/detail.html', {'group':group})

TO clarify, Groups is a model I created, not the default Django model, which is why i imported it from groups.models.

this is what my model for a Post looks like:

from django.db import models
from django.contrib.auth.models import User
from groups.models import Group


class Post(models.Model):
    title = models.CharField(max_length=255, unique=True)
    body = models.TextField()
    likes_total = models.IntegerField(default=0)
    pub_date = models.DateTimeField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)


    def __str__(self):
        return self.name

    def summary(self):
        # return the 1st 100 chars
        return self.body[:100]

    def pub_date_pretty(self):
        # strftime is how to break down time
        return self.pub_date.strftime('%b %e %Y')

I dont get why the error is looking for the group in the auth_group table, when I imported it from my groups.models file! any help would be really appreciated!

Upvotes: 2

Views: 553

Answers (1)

Alasdair
Alasdair

Reputation: 309039

In your previous question, Post.group pointed to the auth.Group model. Now that you have changed it to point to groups.Group, you have to create and run migrations to update your database.

Upvotes: 1

Related Questions