简体   繁体   English

Python Django - 在创建模型时出错 - 使用AbstractUser扩展用户模型

[英]Python Django - getting error while creating model - extending user model with AbstractUser

I am trying to extend the user model using AbstractUser component. 我试图使用AbstractUser组件扩展用户模型。 But I haven't been successful on this. 但我没有成功。 After reseraching lot I wrote my model Employee(Extended user model) but now I get the below error when I do syncdb. 在重新编写之后,我编写了我的模型Employee(扩展用户模型),但现在我在执行syncdb时遇到以下错误。

If anyone can help me by suggesting or running my models.py that would be great. 如果有人可以通过建议或运行我的models.py来帮助我。 when I run syncdb it asks superuser creation after i give the credentials I get a below error. 当我运行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: Please find the complete error which I am getting. 完成追溯:请找到我得到的完整错误。 Let me know if more information required 如果需要更多信息,请与我们联系

(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

You defined emp_id unique but not nullable. 您定义了emp_id unique但不可为空的。

So when you created the superuser, django raises that emp_id can't be null. 所以当你创建超级用户时,django会提出emp_id不能为null。

If you want it as primary key remove that field. 如果您希望它作为主键删除该字段。 If you want define it later put in emp_id field null=True 如果你想稍后定义它,请输入emp_id field null=True

Anyway you can read here https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields 无论如何你可以在这里阅读https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields

Ps I see another error: Ps我看到另一个错误:

self.get_full_name()

But this is the super behaviour so you could delete it at all. 但这是超级行为,所以你可以删除它。

You defined emp_id as unique but not nullable , you can add null=True to the model,but seems to be that you wanna use emp_id as a primari_key , so to ensure that the field can not be null and must be unique you maybe wanna use a models.AutoField : 您将emp_id定义为unique但不可为nullable ,您可以将null=True添加到模型中,但似乎您想要使用emp_id作为primari_key ,因此为了确保该字段不能为null且必须是唯一的,您可能想要使用一个models.AutoField

emp_id = models.AutoField(primary_key=True)

this guarantee that the field is unique an can not be null. 这保证了该字段是唯一的,不能为空。

Now, for the max_length property and the model's name ( Employee ) I think that emp_id will be a number that the company gives you, for example my id in the company where I work is 0001544 , so to avoid that problem you can create a custom manager: 现在,对于max_length属性和模型的名称( Employee ),我认为emp_id将是公司给你的一个数字,例如我工作的公司中的id是0001544 ,所以为了避免这个问题你可以创建一个自定义经理:

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

and then in the models file add this: 然后在模型文件中添加:

from myapp.managers import EmployeManager

and into your Employers Model ass this 并进入你的Employers Model屁股

objects = EmployeManager()

then you run python manage.py syncdb 然后你运行python manage.py syncdb

hope this helps you, any doubt, tell me. 希望这有助于你,任何疑问,告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM