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

如何为Django Admin站点中扩展的用户模型设置字段默认值

问题根源

你遇到的问题和Admin站点的默认逻辑、关联模型的创建机制有关,和字段默认值本身的生效规则无关:

  1. 你给UserProfile字段设置的默认值,只有在UserProfile实例被实际创建的时候才会生效。你当前的配置下,Admin中创建User时不会自动生成关联的UserProfile实例,默认值自然不会生效。
  2. Django Admin的Inline表单默认判定逻辑:如果Inline内的所有字段都保持初始显示值、没有被用户手动修改,Admin会认为这个Inline不需要保存,最终不会创建对应的UserProfile记录,这也是你看到solved显示0但保存后丢失的原因。

解决方案

方案1:使用post_save信号自动创建关联资料(最推荐,全场景生效)

这个方案不管你是通过Admin创建用户,还是用Python代码创建用户,都会自动生成带默认值的UserProfile实例,适配所有场景。

  1. 在你的app目录下新建signals.py,添加如下代码:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import UserProfile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    # 只有新建User的时候才创建关联资料
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.userprofile.save()
  1. 注册信号,打开你app的apps.py,在AppConfig类的ready方法中导入信号:
from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = '你的app名称'

    def ready(self):
        import 你的app名称.signals

方案2:修改Admin配置强制保存Inline(仅Admin场景生效)

如果你只需要在Admin站点创建用户时生效,可以修改admin.py的Inline配置,要求必须保存关联资料:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'User Profile'
    # 强制要求填写该Inline,避免Admin跳过保存
    required = True
    extra = 1
    max_num = 1

额外优化建议

你当前profile_pic字段的默认值写死了/media/前缀,建议修改为相对路径,后续修改MEDIA_URL配置时不需要改代码:

profile_pic = models.ImageField(upload_to='profile_pic', default="profile_pic/default-profile.jpg")

内容的提问来源于stack exchange,提问作者blastzit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 06:24:02