我正在尝试使用AbstractUser组件扩展用户模型。但我没有成功。在重新编写之后,我编写了我的模型Employee(扩展用户模型),但现在我在执行syncdb时遇到以下错误。
如果有人可以通过建议或运行我的models.py来帮助我。当我运行syncdb时,它询问超级用户创建后我给出了凭据我收到了以下错误。
Error : (Complete traceback is pasted after the models.py)
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: epi_employee.emp_id may not be NULL
My models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
# Create your models here.
class Employee(AbstractUser):
emp_id = models.IntegerField('Employee Id', max_length=5,unique=True)
dob = models.DateField('Date of Birth', null=True,blank=True)
def __unicode__(self):
return self.get_full_name
class Department(models.Model):
name = models.CharField('Department Name',max_length=30, unique=True,default=0)
def __unicode__(self):
return self.name
class Report(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
dept = models.ForeignKey(Department, verbose_name="Department")
report1 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Primary Supervisor',related_name='Primary')
report2 = models.ForeignKey(Employee,null=True,blank=True, verbose_name=u'Secondary Supervisor',related_name='Secondary')
def __unicode__(self):
return self.user
def upload_to(instance, filename):
return 'images/%s/%s' % (instance.user.username, filename)
class thumbnail((models.Model)):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
image = models.ImageField('Profile Pic',null=True, blank=True, upload_to=upload_to)
def __unicode__(self):
return self.user
class Passport(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
passport = models.CharField('Passport Number',max_length=15)
passportissue = models.CharField('Issuing City',max_length=15, default='Bangalore')
passportcountry = models.CharField('Issuing City',max_length=15, default='India')
passportstart = models.DateField('Valid From', null=True,blank=True)
passportend = models.DateField('Valid Till', null=True,blank=True)
def __unicode__(self):
return self.user
class CurrentAddress(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
address = models.TextField('Current Address')
city = models.CharField('City', max_length=20, default = 'Bangalore')
state = models.CharField('State', max_length=20, default= 'Karnataka')
country = models.CharField('Country', max_length=20, default = 'India')
mobile1 = models.IntegerField('Mobile1',max_length=12)
mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
email = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.user
COMPLETE TRACE BACK:请找到我收到的完整错误。如果需要更多信息,请告诉我
(testenv1) F:\djangoenv\testenv1\employee>python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table django_content_type
Creating table django_session
Creating table epi_employee_groups
Creating table epi_employee_user_permissions
Creating table epi_employee
Creating table epi_department
Creating table epi_report
Creating table epi_thumbnail
Creating table epi_passport
Creating table epi_currentaddress
You just installed Django's auth system, which means you don't have any superuse
rs defined.
Would you like to create one now? (yes/no): yes
Username: admin
Email address: admin@admin.com
Password:
Password (again):
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 399, in execute_from_command_line
utility.execute()
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 285, in execute
output = self.handle(*args, **options)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 415, in handle
return self.handle_noargs(**options)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\commands\
syncdb.py", line 112, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\sql.py",
line 216, in emit_post_sync_signal
interactive=interactive, db=db)
File "F:\djangoenv\testenv1\lib\site-packages\django\dispatch\dispatcher.py",
line 185, in send
response = receiver(signal=self, sender=sender, **named)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\management\_
_init__.py", line 126, in create_superuser
call_command("createsuperuser", interactive=True, database=db)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\__init__.
py", line 159, in call_command
return klass.execute(*args, **defaults)
File "F:\djangoenv\testenv1\lib\site-packages\django\core\management\base.py",
line 285, in execute
output = self.handle(*args, **options)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\management\c
ommands\createsuperuser.py", line 141, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user
_data)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\models.py",
line 195, in create_superuser
**extra_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\contrib\auth\models.py",
line 186, in _create_user
user.save(using=self._db)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
545, in save
force_update=force_update, update_fields=update_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\base.py", line
687, in _do_insert
using=using, raw=raw)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\manager.py", li
ne 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\query.py", line
1511, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\models\sql\compiler.py
", line 898, in execute_sql
cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 53, in execute
return self.cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\utils.py", line 99, in
__exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\util.py", lin
e 53, in execute
return self.cursor.execute(sql, params)
File "F:\djangoenv\testenv1\lib\site-packages\django\db\backends\sqlite3\base.
py", line 450, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: epi_employee.emp_id may not be NULL
答案 0 :(得分:1)
您定义了emp_id
unique
但不可为空。
因此,当您创建超级用户时,django会提出emp_id
不能为空。
如果您希望将其作为主键删除该字段。
如果您想稍后定义它,请放入emp_id字段null=True
无论如何,你可以在这里阅读https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields
P.S。我看到另一个错误:
self.get_full_name()
但这是超级行为,所以你可以删除它。
答案 1 :(得分:1)
您将emp_id
定义为unique
但未nullable
,您可以将null=True
添加到模型中,但似乎您希望使用emp_id
作为primari_key
一个models.AutoField
,所以为了确保该字段不能为空并且必须是唯一的,您可能想要使用emp_id = models.AutoField(primary_key=True)
:
max_length
这保证该字段是唯一的,不能为空。
现在,对于Employee
属性和模型的名称(emp_id
),我认为0001544
将是公司为您提供的数字,例如我在公司的ID我的工作是from django.contrib.auth.models import BaseUserManager
class EmployeManager(BaseUserManager):
def create_user(self, username, email,emp_id, password=None):
if not username:
raise ValueError('Employers must have an username.')
if not email:
raise ValueError('Employers must have an email address.')
if not emp_id:
raise ValueError('Employers must have an employer id')
user = self.model(username=username, email=self.normalize_email(email), emp_id=emp_id)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, emp_id, password):
user = self.create_user(username, email, emp_id, password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
,所以为了避免这个问题,你可以创建一个自定义管理器:
from myapp.managers import EmployeManager
然后在模型文件中添加:
Employers Model
进入你的objects = EmployeManager()
屁股
python manage.py syncdb
然后你运行{{1}}
希望这对你有所帮助,有任何疑问,请告诉我。