【发布时间】:2017-10-12 10:42:56
【问题描述】:
在 django.contrib.auth.models.User 中,first_name 和 last_name 字段都有 blank=True。如何在我自己的模型中制作blank=False, null=False?
这里是我的实现,基本按照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
信号.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
【问题讨论】:
-
您应该从原始 User 类派生模型。
-
@KlausD。你的意思是直接继承
User?但是文档中的示例代码写的是class Employee(models.Model):而不是class Employee(User):... -
@KlausD。这样做会给我一个错误:
django.core.exceptions.FieldError: Local field 'first_name' in class 'Fellow' clashes with field of the same name from base class 'User'.
标签: python django database authentication model