Django Admin保存报错:Field 'site_id'无默认值问题
Let's walk through why this error is popping up and how to fix it quickly.
1. First, make sure your migrations are applied
You added default=1 to the site field in your User model, but if that change hasn't been synced to your database, the site_id column in the database still doesn't have a default value set.
Run these commands to update your database schema:
python manage.py makemigrations python manage.py migrate
This is the most common fix—Django won't apply model changes to the database automatically, so migrations are mandatory here.
2. Verify that a Site object with ID=1 actually exists
Your default is hardcoded to 1, but if there's no Site instance with that ID in your database, even with migrations applied, you'll hit this error (since foreign keys require a valid, existing object to link to).
Check via Django shell:
python manage.py shell from django.contrib.sites.models import Site print(Site.objects.filter(id=1).exists())
- If it returns
False, create a Site with ID=1 (you can do this via the Django Admin or shell), or adjust the default to use an existing Site's ID. - For a more flexible approach, you can use a lambda to default to the first available Site:
Just make sure at least one Site exists before saving any User objects!site = models.ForeignKey(Site, related_name='users', default=lambda: Site.objects.first().id)
3. Check your Admin configuration
If you're not displaying the site field in your User Admin, Django should fall back to the model's default—but if the database doesn't recognize that default (because migrations weren't run), it'll throw an error.
Update your User Admin to explicitly include the site field:
from django.contrib.auth.admin import UserAdmin from django.contrib import admin from .models import User @admin.register(User) class CustomUserAdmin(UserAdmin): fieldsets = UserAdmin.fieldsets + ( ('Additional Details', {'fields': ('address', 'site')}), )
This ensures the Admin uses your model's default value correctly, or lets users select a Site if needed.
4. Check your database's strict mode (for MySQL users)
If you're using MySQL with strict mode enabled (like STRICT_TRANS_TABLES), the database might override Django's default settings and enforce that site_id has a default.
You can verify the column's default value by checking your table structure directly:
DESCRIBE auth_user; -- Replace with your actual User table name
If the site_id column's Default isn't set to 1, re-run your migrations to ensure the change is applied properly.
内容的提问来源于stack exchange,提问作者pasichnyk.oleh

