创建关联群组的Django帖子时触发IntegrityError错误求助
Hey there, let's break down this error and get your post creation working smoothly!
What's Causing the Issue?
The error IntegrityError at /posts/create/18/: Key (group_id)=(18) is not present in table "auth_group" reveals a critical mismatch:
- Your view is fetching a group from your custom
groups.models.Groupmodel (usingget_object_or_404(Group, pk=group_id)), which has an ID of 18. - But your
Postmodel'sgroupfield is actually linked to Django's built-inauth_grouptable (fromdjango.contrib.auth.models.Group), where no group with ID 18 exists.
The database rejects the save because you're trying to connect the post to a group that doesn't exist in the table the foreign key is constrained to.
Step-by-Step Solutions
1. Correct the Post Model's Foreign Key
First, check your posts/models.py—you likely imported the wrong Group model by mistake.
Incorrect current code:
from django.contrib.auth.models import Group class Post(models.Model): # Links to Django's built-in auth groups (not your custom groups) group = models.ForeignKey(Group, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() # Other fields...
Fixed code:
# Import YOUR custom Group model instead from groups.models import Group class Post(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() # Other fields...
2. Update Database Migrations
After fixing the model, apply the changes to update the database's foreign key constraints:
python manage.py makemigrations python manage.py migrate
3. Polish Your View Code (Bonus)
Your view has a couple of small issues to make it more robust:
- The duplicate check
if request.POST['body'] and request.POST['body']:should validate both title and body. - Use the fetched
groupobject directly instead of manually settinggroup_idto avoid ID mismatches.
Improved view code:
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': # Use .get() to avoid KeyError if fields are missing title = request.POST.get('title') body = request.POST.get('body') if title and body: post = Post( title=title, body=body, group=group, # Directly assign the valid group object created_at=timezone.now() # Add if your model includes a creation time field ) post.save() # Add a redirect or success message here for better UX # Handle GET request (render the post creation form) return render(request, 'posts/create.html', {'group': group})
Verify the Fix
Once you've applied these changes:
- Confirm your custom
groups.Grouptable has a group with ID 18 (check via Django admin orpython manage.py shell). - Try creating the post again—this time the foreign key will point to the correct table, and the save should succeed.
内容的提问来源于stack exchange,提问作者Nader

