2016-04-27 265 views
1

我目前正在学习Python。我试图添加一个新字段(product_group)作为基本Django User类的外键。但是,当我试图“蟒蛇manage.py迁移”我收到此错误信息:Django 1.9:“ValueError:无效文字为int()与基地10:'未指定'”

> C:\Users\Дима\PycharmProjects\SupportYourApp2>python manage.py migrate 
> Operations to perform: Apply all migrations: Authentication_System, 
> contenttypes, admin, auth, sessions Running migrations: Rendering 
> model states... DONE Applying 
> Authentication_System.0003_customuser_product_group...Traceback (most 
> recent call last): File "manage.py", line 10, in <module> 
>  execute_from_command_line(sys.argv) File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 350, in execute_f rom_command_line 
>  utility.execute() File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 342, in execute 
>  self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 348, in run_from_argv 
> 
>  self.execute(*args, **cmd_options) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 399, in execute 
>  output = self.handle(*args, **options) File "C:\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", 
> line 200, in h andle 
>  executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 92, in migrate 
>  self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 121, in _migrate_al l_forwards 
>  state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 198, in apply_migra tion 
>  state = migration.apply(state, schema_editor) File "C:\Python35-32\lib\site-packages\django\db\migrations\migration.py", 
> line 123, in apply 
>  operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", 
> line 62, in dat abase_forwards 
>  field, File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 221, in add_fie ld 
>  self._remake_table(model, create_fields=[field]) File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 103, in _remake 
> _table 
>  self.effective_default(field) File "C:\Python35-32\lib\site-packages\django\db\backends\base\schema.py", 
> line 210, in effective_ default 
>  default = field.get_db_prep_save(default, self.connection) File "C:\Python35-32\lib\site-packages\django\db\models\fields\related.py", 
> line 910, in get_db_pr ep_save 
>  return self.target_field.get_db_prep_save(value, connection=connection) File 
> "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 728, in get_db_p rep_save 
>  prepared=False) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 968, in get_db_p rep_value 
>  value = self.get_prep_value(value) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 976, in get_prep 
> _value 
>  return int(value) ValueError: invalid literal for int() with base 10: 'Not specified' 
> 
> C:\Users\Дима\PycharmProjects\SupportYourApp2>python manage.py migrate 
> Operations to perform: Apply all migrations: contenttypes, admin, 
> Authentication_System, auth, sessions Running migrations: Rendering 
> model states... DONE Applying 
> Authentication_System.0003_customuser_product_group...Traceback (most 
> recent call last): File "manage.py", line 10, in <module> 
>  execute_from_command_line(sys.argv) File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 350, in execute_f rom_command_line 
>  utility.execute() File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 342, in execute 
>  self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 348, in run_from_argv 
> 
>  self.execute(*args, **cmd_options) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 399, in execute 
>  output = self.handle(*args, **options) File "C:\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", 
> line 200, in h andle 
>  executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 92, in migrate 
>  self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 121, in _migrate_al l_forwards 
>  state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 198, in apply_migra tion 
>  state = migration.apply(state, schema_editor) File "C:\Python35-32\lib\site-packages\django\db\migrations\migration.py", 
> line 123, in apply 
>  operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", 
> line 62, in dat abase_forwards 
>  field, File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 221, in add_fie ld 
>  self._remake_table(model, create_fields=[field]) File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 103, in _remake 
> _table 
>  self.effective_default(field) File "C:\Python35-32\lib\site-packages\django\db\backends\base\schema.py", 
> line 210, in effective_ default 
>  default = field.get_db_prep_save(default, self.connection) File "C:\Python35-32\lib\site-packages\django\db\models\fields\related.py", 
> line 910, in get_db_pr ep_save 
>  return self.target_field.get_db_prep_save(value, connection=connection) File 
> "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 728, in get_db_p rep_save 
>  prepared=False) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 968, in get_db_p rep_value 
>  value = self.get_prep_value(value) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 976, in get_prep 
> _value 
>  return int(value) ValueError: invalid literal for int() with base 10: 'Not specified' 
> 
> C:\Users\Дима\PycharmProjects\SupportYourApp2>python manage.py 
> makemigrations Migrations for 'Authentication_System': 
> 0017_auto_20160427_1859.py: 
>  - Alter field product_group on customuser 
> 
> C:\Users\Дима\PycharmProjects\SupportYourApp2>python manage.py migrate 
> Operations to perform: Apply all migrations: auth, admin, 
> Authentication_System, contenttypes, sessions Running migrations: 
> Rendering model states... DONE Applying 
> Authentication_System.0003_customuser_product_group...Traceback (most 
> recent call last): File "manage.py", line 10, in <module> 
>  execute_from_command_line(sys.argv) File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 350, in execute_f rom_command_line 
>  utility.execute() File "C:\Python35-32\lib\site-packages\django\core\management\__init__.py", 
> line 342, in execute 
>  self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 348, in run_from_argv 
> 
>  self.execute(*args, **cmd_options) File "C:\Python35-32\lib\site-packages\django\core\management\base.py", 
> line 399, in execute 
>  output = self.handle(*args, **options) File "C:\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", 
> line 200, in h andle 
>  executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 92, in migrate 
>  self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 121, in _migrate_al l_forwards 
>  state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\executor.py", 
> line 198, in apply_migra tion 
>  state = migration.apply(state, schema_editor) File "C:\Python35-32\lib\site-packages\django\db\migrations\migration.py", 
> line 123, in apply 
>  operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File 
> "C:\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", 
> line 62, in dat abase_forwards 
>  field, File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 221, in add_fie ld 
>  self._remake_table(model, create_fields=[field]) File "C:\Python35-32\lib\site-packages\django\db\backends\sqlite3\schema.py", 
> line 103, in _remake 
> _table 
>  self.effective_default(field) File "C:\Python35-32\lib\site-packages\django\db\backends\base\schema.py", 
> line 210, in effective_ default 
>  default = field.get_db_prep_save(default, self.connection) File "C:\Python35-32\lib\site-packages\django\db\models\fields\related.py", 
> line 910, in get_db_pr ep_save 
>  return self.target_field.get_db_prep_save(value, connection=connection) File 
> "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 728, in get_db_p rep_save 
>  prepared=False) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 968, in get_db_p rep_value 
>  value = self.get_prep_value(value) File "C:\Python35-32\lib\site-packages\django\db\models\fields\__init__.py", 
> line 976, in get_prep 
> _value 
>  return int(value) ValueError: invalid literal for int() with base 10: 'Not specified' 

这里是我的models.py文件:

from django.db import models 
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin 
from django.utils import timezone 
from django.core.mail import send_mail 
from django.utils.http import urlquote 
from django.utils.translation import ugettext_lazy as _ 
from django.core import validators 

# Create your models here. 
class ProductsGroup(models.Model): 
    class Meta: 
     db_table = 'Group of products' 

    groupName = models.CharField(max_length = 50, unique = True) 

    def __str__(self): 
     return format(self.groupName) 

######################################### USER MODEL ######################################### 
class CustomUserManager(BaseUserManager): 
    use_in_migrations = True 

    def _create_user(self, email, password, **extra_fields): 
     """ 
     Creates and saves a User with the given username, email and password. 
     """ 
     if not email: 
      raise ValueError('The given email must be set') 
     email = self.normalize_email(email) 
     user = self.model(email=email, **extra_fields) 
     user.set_password(password) 
     user.save(using=self._db) 
     return user 

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

    def create_superuser(self, email, password, **extra_fields): 
     extra_fields.setdefault('is_staff', True) 
     extra_fields.setdefault('is_superuser', True) 

     if extra_fields.get('is_staff') is not True: 
      raise ValueError('Superuser must have is_staff=True.') 
     if extra_fields.get('is_superuser') is not True: 
      raise ValueError('Superuser must have is_superuser=True.') 

     return self._create_user(email, password, **extra_fields) 

class CustomUser(AbstractBaseUser, PermissionsMixin): 
    email = models.EmailField(_('email address'), blank=False, unique=True) 
    first_name = models.CharField(_('first name'), max_length=30, blank=True) 
    last_name = models.CharField(_('last name'), max_length=30, blank=True) 
    username = models.CharField(
     _('username'), 
     max_length=30, 
     unique=True, 
     help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'), 
     validators=[ 
      validators.RegexValidator(
       r'^[\[email protected]+-]+$', 
       _('Enter a valid username. This value may contain only ' 
        'letters, numbers ' 'and @/./+/-/_ characters.') 
      ), 
     ], 
     error_messages={ 
      'unique': _("A user with that username already exists."), 
     }, 
    ) 
    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=True, 
     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) 

    product_group = models.ForeignKey(ProductsGroup, default=2) 

    objects = CustomUserManager() 

    USERNAME_FIELD = 'email' 
    REQUIRED_FIELDS = ['username',] 


    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): 
     full_name = '%s %s' % (self.first_name, self.second_name) 
     return full_name.strip() 

    def get_short_name(self): 
     return self.first_name 

    def emai_user(self, subject, message, from_email = None): 
     send_mail(subject, message, from_email, [self.email]) 

我将非常任并欣赏意见。

+0

试试这个默认值转换成文字 'PRODUCT_GROUP = models.ForeignKey(ProductsGroup,默认值=“2”)' 或者你必须首先使用id从ProductsGroup表,并设置得到它传递对象对象的默认值。 –

+0

@MuhammadShoaib谢谢,但将默认值转换为文字不是解决方案。 “您必须首先使用ProductsGroup表中的ID获取该对象,并将默认值设置为对象来传递该对象。” - 我不太确定如何做到这一点。也许你可以给我一些伪代码样本? –

回答

0

你的情况很难给你任何提示。也许这是因为您的Productsgroup型号中没有任何条目。但作为默认值,您可以给2(这是我在数据库中的一个条目的标识),就像这样default=2。如果您还没有任何输入,这可能会导致问题。

但是,实际上,您不应该扩展这样的User模型。正如本文中提到:

Think carefully before handling information not directly related to authentication in your custom User Model.

It may be better to store app-specific user information in a model that has a relation with the User model.

ProductGroup似乎并不具有认证系统任何关系,所以,如果你想要一些额外的信息添加到您的用户,则可以延长Django的内置的用户模型简单地通过创建另一个模型并将其与oneToOneField关联到内置的用户模型。 你可以得到关于该here的完整解释。

+0

谢谢。 'oneToOneField'关系是一个非常好的解决方案,我之前已经完成了它(它工作正常)。在这个代码示例中,我试图了解如何使用这种确切的方法来扩展基本的Django用户模型。 'ProductGroup'与'User'相关为'oneToManyField'(一个产品组可以有多个用户,一个用户只能有一个组)。 –

+0

我正试图将条目添加到数据库。我正在尝试'ForeignKey(ProductsGroup)'和'ForeignKey(ProductsGroup,blank = True)' - 结果与此消息中的结果相同。 所以,如果您有任何其他建议,请让我知道。 –

+0

'django的内置组功能怎么样? – sehrob

0

解决方案是创建一个新项目。 正如他们在Django 1.9 documentation说:

Due to limitations of Django’s dynamic dependency feature for swappable models, you must ensure that the model referenced by AUTH_USER_MODEL is created in the first migration of its app (usually called 0001_initial); otherwise, you will have dependency issues.

我也为了解决这个问题,改变product_group = models.ForeignKey(ProductsGroup, blank=True, null=True)models.py同时创造超级用户:

django.db.utils.IntegrityError: NOT NULL constraint failed: Authentication_System_customuser.product_group_id

现在一切工作。

相关问题