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

Django自定义用户模型迁移报错:无法解析关联模型'users.customuser'

Hey there, let's break down why you're hitting this error when running python manage.py migrate and how to fix it. Your managers.py and models.py code looks solid—this issue almost always boils down to missing configuration or leftover migration conflicts.

1. You haven't set AUTH_USER_MODEL in your project's settings

This is the most common culprit. Django needs explicit instruction to use your custom user model instead of the default User class.

Open your project's settings.py file and add this line (usually near the app configuration section):

AUTH_USER_MODEL = 'users.CustomUser'
  • Note the format: app_name.ModelName (your app is named users, and your model class is CustomUser—capitalization matters here!)

2. Leftover migration files are causing conflicts

If you ran makemigrations or migrate before setting AUTH_USER_MODEL, Django already created migrations for the default auth app that reference the old User model. These will clash with your new custom model. Here's how to clean up:

  • Navigate to your users app's migrations folder. Delete all files except __init__.py.
  • Delete the db.sqlite3 file in your project root (only do this if you're in a development environment and don't need to preserve existing data!).
  • Run these commands in sequence:
    python manage.py makemigrations
    python manage.py migrate
    

3. Double-check model references (if you have other models)

If you add other models later that reference the user model, make sure you use the correct syntax to avoid similar errors:

  • Best practice: Use models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ...) (this dynamically references your configured user model)
  • Alternatively, import the model directly: from users.models import CustomUser then models.ForeignKey(CustomUser, on_delete=models.CASCADE, ...)
  • Avoid lowercase references like 'users.customuser'—Django expects the model name to match the class name's capitalization.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:30:35