在Django中使用Migration命令时如何获取求解值错误

时间:2019-07-12 07:27:11

标签: python django django-models

我正在使用django frmaework来处理应用程序,并且我的make migration命令运行正常,但是migration命令给出了错误

我使用了Django frmawork,但是迁移命令givig错误 (ValueError:以10为基数的int()无效文字:“超级管理员”)

这是我的models.py文件:

`import uuid
from django.contrib.auth.models import AbstractBaseUser, 
BaseUserManager
from django.db import models

class CustomUserManager(BaseUserManager):
def create_user(self, email, password, **kwargs):
    if not email or not password:
        raise ValueError('User must have a username and password')

    user = self.model(
        email=CustomUserManager.normalize_email(email),
        **kwargs
    )

    user.set_password(password)
    user.save()

    return user

def create_superuser(self, email, password, **kwargs):
    user = self.create_user(email, password, **kwargs)

    user.is_admin = True
    user.is_staff = True
    user.save()

    return user
class User(AbstractBaseUser):

SUPER_ADMIN = 1
STUDENT = 2
TEACHER = 3
ROLE_CHOICES = (
    (STUDENT, 'Student'),
    (SUPER_ADMIN, 'Super Admin'),
    (TEACHER , 'Teacher'),
)
first_name = models.CharField(max_length=255, null=False)
last_name = models.CharField(max_length=255, null=False)
email = models.EmailField(null=False, unique=True)
is_active = models.BooleanField(default=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
is_staff = models.BooleanField(default=False)

# Add custom fields here
api_token = models.UUIDField(default=uuid.uuid4, editable=False)
token_created_date = models.DateTimeField(auto_now_add=True)
role = models.SmallIntegerField(choices = ROLE_CHOICES, null = True)

objects = CustomUserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']

def get_full_name(self):
    return self.first_name + " " + self.last_name

def get_short_name(self):
    return self.first_name

def has_perm(self, perm, obj=None):
    return self.is_staff

def has_module_perms(self, app_label):
    return self.is_staff

def api_token_reset(self):
    self.api_token = models.UUIDField(default=uuid.uuid4, editable=False)

class Meta:
    ordering = ('created_on',)
    db_table = 'users'

def __unicode__(self):
    return self.get_full_name()`

这是views.py文件:

`from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect

from .forms import SignUpForm
from django.contrib.auth.forms import AuthenticationForm

from django.http import HttpResponseRedirect
from django.views.generic import FormView

@login_required
def home(request):
return render(request, 'index.html')

def signupchoice(request):
if request.method == 'POST':
    if 'teacher' in request.POST:
        #role = "Teacher"
        print("hey Teacher")

        return redirect('signup')
    elif 'student' in request.POST:
        #role = "Student"
        print("hey student")

        return redirect('signup')

return render(request, 'signupchoice.html')

def signup(request):
if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        user = form.save()
        return redirect('index')
else:
    form = SignUpForm()
#print(role)
return render(request, 'signup.html', {'form': form})

def index(request):
return render(request, "index.html")

class LoginView(FormView):
form_class = AuthenticationForm
template_name = 'login.html'

def form_valid(self, form):
    username = form.cleaned_data['username']
    password = form.cleaned_data['password']
    user = authenticate(username  = username, password = password)
    print(user.role)

    if user is not None and user.is_active:
        login(self.request, user)
        return redirect("index")
    else:
        return self.form_invalid(form)`  

这是运行命令-python manage.py migrate时的错误

`Operations to perform:
 Apply all migrations: admin, auth, contenttypes, exam_app, sessions
Running migrations:
Applying exam_app.0003_auto_20190708_1935...Traceback (most recent call last):
 File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/migrations/migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 114, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 509, in alter_field
old_db_params, new_db_params, strict)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 311, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 170, in _remake_table
'default': self.quote_value(self.effective_default(new_field))
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 224, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 767, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/firestorm/Desktop/exam_app/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1826, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'Super Admin'`

这是迁移文件:

`from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
    ('exam_app', '0002_user_role'),
]

operations = [
    migrations.AlterField(
        model_name='user',
        name='role',
        field=models.SmallIntegerField(choices=[('Student', 'Student'), ('Super Admin', 'Super Admin'), ('Teacher', 'Teacher')], default='Super Admin'),
    ),
]

`

1 个答案:

答案 0 :(得分:1)

如您所见,由于某种原因,您的迁移文件0003_auto_20190708_1935无法反映代码:字段选择值是字符串(“学生”等),而不是代码中的整数。

大概是在将代码更改为使用整数之前创建了该迁移。您应该删除该迁移文件以及该应用中的所有后续迁移文件,然后重新运行makemigrations