Django - IntegrityError:NOT NULL约束失败:

时间:2017-07-08 07:46:20

标签: django debugging django-models

我正在尝试将ContactNumber添加到我的模型中。迁移工作但是,为什么我在尝试createuperuser时遇到此错误。请有人解释一下。

我的模特:

class MyUser(AbstractBaseUser, PermissionsMixin):
    DESIGNATION_CHOICES = (
        ('Faculty', 'Faculty'),
        ('Student', 'Student'),
    )
    STUDENT_CHOICES = (('M.Sc', 'M.Sc'),
                       ('PhD', 'PhD'),
                       ('Research Fellow', 'Research Fellow'),
                       )

    LABORATORY_CHOICES = (
        ('Select', 'Select'),
        ('Bioinformatics', 'Bioinformatics Lab'),
        ('Marker lab', 'Marker Lab'),
        ('Microbiology lab', 'Microbiology Lab'),
        ('RNA lab', 'RNA Lab'),
        ('Transformation lab', 'Transformation Lab'),
    )

    email = models.EmailField(_('email address'), max_length=254, unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    designation = models.CharField(null=True, max_length=1, default=None,
                                   choices=DESIGNATION_CHOICES, verbose_name='Select your designation')
    student_designation = models.CharField(null=True, max_length=1, default=None,
                                           choices=STUDENT_CHOICES, verbose_name='Select your designation')
    registration_id = models.CharField(_('registration id'), max_length=30, unique=True,
                                       default='', validators=[RegexValidator(r'^\d{1,10}$')])
    laboratory = models.CharField(_('laboratory'), max_length=50, choices=LABORATORY_CHOICES, default=False, blank=False)
    date_of_birth = models.DateField(blank=True, default='')
    permanent_address = models.TextField(max_length=500, blank=True, default='')
    corresponding_address = models.TextField(max_length=500, blank=True, default='')
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,10}$',
                                 message="Phone number must be entered in the format: '+999999999'."
                                         " Up to 10 digits allowed.")

    contact_number = models.IntegerField(_('contact number'), validators=[phone_regex], unique=True, null=True, blank=True)

    guardian_name = models.CharField(_('guardian name'), max_length=30, blank=True)
    guardian_contact_number = models.CharField(_('guardian contact number'), max_length=10,
                                               validators=[RegexValidator(r'^\d{1,10}$')])

    is_staff = models.BooleanField(_('staff status'), default=False,
                                   help_text=_('Designates whether the user can log into this admin site.'))
    is_active = models.BooleanField(_('active'), default=False,
                                    help_text=_('Designates whether this user should be treated as '
                                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    groups = models.ManyToManyField(Group, verbose_name=_('groups'),
                                    blank=True, help_text=_('The groups this user belongs to. A user will '
                                                            'get all permissions granted to each of '
                                                            'his/her group.'),
                                    related_name="tmp_user_set", related_query_name="user")

    user_permissions = models.ManyToManyField(Permission,
                                              verbose_name=_('user permissions'), blank=True,
                                              help_text=_('Specific permissions for this user.'),
                                              related_name="tmp_user_set", related_query_name="user")

    objects = manager.CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.email)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])


class CustomUserManager(BaseUserManager):
    def _create_user(self, email, password,
                     is_staff, is_superuser, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, last_login=now,
                          date_joined=now, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(email, password, False, False,
                                 **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True,
                                 **extra_fields)

追溯:

追踪(最近一次呼叫最后一次):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 31, in create_superuser
    **extra_fields)
  File "/home/surajit/website/PubNet/user_profile/manager.py", line 22, in _create_user
    user.save(using=self._db)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 1060, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/compiler.py", line 1099, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/backends/sqlite3/base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: user_profile_myuser.contact_number

请帮忙。

0 个答案:

没有答案