2016-04-27 133 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

現在一切工作。

相關問題