在django.contrib.auth.models.User
中,first_name
和last_name
字段都有blank=True
。我怎樣才能使他們在我自己的模型blank=False, null=False
?在Django中需要first_name和last_name用戶模型
這裏是我的實現,基本上遵循Extending the existing User model說明:
models.py
class Fellow(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE
)
first_name = models.CharField(
_("first_name"),
max_length=30,
)
last_name = models.CharField(
_("last_name"),
max_length=30,
)
# other fields omitted
from . import signals
signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Fellow
@receiver(post_save, sender=User)
def create_fellow_on_user_create(sender, instance, created, **kwargs):
if created:
Fellow.objects.create(user=instance)
然而,我在python manage.py shell
測試時得到了一個錯誤:
>>> f = Fellow.objects.create(username='username', password='passwd')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/base.py", line 571, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'username' is an invalid keyword argument for this function
您應該從原始用戶類派生您的模型。 –
@KlausD。你的意思是直接繼承'User'嗎?但是文檔中的示例代碼寫入'Employee Employee(models.Model):'而不是'Employee Employee(用戶):'... –
@KlausD。這樣做會給我一個錯誤:'django.core.exceptions.FieldError:'Fellow'類中的本地字段'first_name'與基類'User'中的同名字段發生衝突。 –