Django 3.2中Account模型email字段冲突报错排查求助
Hey there, let's sort out this field clash error you're hitting with your Django custom user model!
The root cause of your SystemCheckError is a small oversight in your Account class definition. Take a look at this line:
USERNAME_FIELD = email
You're assigning the field object email directly to USERNAME_FIELD, but Django expects a string containing the field name here. When you pass the field object instead of the string, Django's system check ends up interpreting it as a duplicate field definition, hence the clash with your existing email field.
The Fix
Change that line to use the string literal of your field name:
USERNAME_FIELD = "email"
Here's the corrected snippet of your Account class for clarity:
class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) name = models.CharField(max_length=50) reputation = models.BigIntegerField(default=1) downvote_count = models.IntegerField(default=0) # mandatory fields created_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) # Fixed line below USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "first_name", "last_name"] objects = AccountManager() # ... rest of your methods
Why This Works
Django's AbstractBaseUser uses USERNAME_FIELD to know which field should act as the unique identifier for authentication (replacing the default username field). It requires the name of the field as a string, not the field instance itself. By passing the string "email", you're telling Django exactly which existing field to use, eliminating the duplicate field conflict.
Verify & Apply
After making this change:
- Run
python manage.py checkto confirm no more system errors - Then run
python manage.py makemigrationsfollowed bypython manage.py migrate
This should resolve the field clash issue you're facing!
内容的提问来源于stack exchange,提问作者user16987274

