You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Admin保存报错:Field 'site_id'无默认值问题

Fix: "Field 'site_id' doesn't have a default value" in Django Admin when saving objects

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:
    site = models.ForeignKey(Site, related_name='users', default=lambda: Site.objects.first().id)
    
    Just make sure at least one Site exists before saving any User objects!

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:18:08