I am new to django and I am creating my models but I am having trouble when trying to add a foreign key to another model. here's my models:
from django.db import models
class User(models.Model):
user_id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=30)
surname = models.CharField(max_length=30)
role = models.CharField(max_length=10)
address = models.CharField(max_length=50)
email = models.EmailField(max_length=30)
password = models.CharField(max_length=20)
phone = models.IntegerField()
GPA = models.FloatField(max_length=5)
Gender = models.CharField(max_length=1)
def __str__(self):
return self.user_id
class Login(models.Model):
user_id = models.ForeignKey(User, on_delete=models.CASCADE, default='00000')
email = models.EmailField(max_length=30)
password = models.CharField(max_length=20)
def __str__(self):
return self.email
When I type makemigrations I get this:
You are trying to change the nullable field 'user_id' on login to non-nullable without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
3) Quit, and let me add a default in models.py
Select an option: 3
So I added a default value but I am getting this error when I tried to migrate. I tried to change user_id from User to AutoField so I don't have to add any default value but it is still giving me this error. Plus I don't know why it says user_id_id at the end. Can anyone help me out with this?
Running migrations:
Rendering model states... DONE
Applying login.0003_login_user_id...Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\base.py", line 112, in execute
return self.cursor.execute(query, args)
File "C:\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler
raise errorvalue
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 223, in execute
res = self._query(query)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 379, in _query
rowcount = self._do_query(q)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 342, in _do_query
db.query(q)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 286, in query
_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1067, "Invalid default value for 'user_id_id'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pycharm\django_manage.py", line 41, in <module>
run_module(manage_file, None, '__main__', True)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 182, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:/Users/Desktop/Project/TSL/mysite\manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 399, in execute
output = self.handle(*args, **options)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\AppData\Local\Programs\Python\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:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 121, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\AppData\Local\Programs\Python\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:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards
field,
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\schema.py", line 50, in add_field
super(DatabaseSchemaEditor, self).add_field(model, field)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 396, in add_field
self.execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 110, in execute
cursor.execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\base.py", line 112, in execute
return self.cursor.execute(query, args)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler
raise errorvalue
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 223, in execute
res = self._query(query)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 379, in _query
rowcount = self._do_query(q)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 342, in _do_query
db.query(q)
File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 286, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1067, "Invalid default value for 'user_id_id'")
Process finished with exit code 1
First of all, as mentioned in the comments, do NOT name the ForeignKey field user_id, but user. This will create a column called user_id in the db table and your model instance's user attribute will return a User instance while its auto-generated attribute user_id will return that user's id.
As for specifying a default value for a ForeignKey. If you do that on the model, make sure you provide an existing User. If you choose to provide a one-off default during makemigrations (if you select option 1), make sure to provide the primary key of an existing User. Alternatively, make sure there are no existing Login records in the db.
django automatically creates a primary keys for all your models, and it manages it internally.
Unless you have a very specific reason, you do not want to be managing or fiddling with the primary key manually.
Now, the specific reason for your error is that once you changed the type of field from CharField to AutoField, it changed the type from a character to an integer - but then you are assigning it a default value of a string (character), which is causing error from your database.
My best advice for you is to start from scratch. You don't need the Login model at all, django comes with authentication built-in and its own "user" model.
from django.db import models
# Renamed from User to MyUser,
# User is a built-in model that comes with django
# and is used when logging people into the system
# https://docs.djangoproject.com/en/1.9/topics/auth/default/
class MyUser(models.Model):
name = models.CharField(max_length=30)
surname = models.CharField(max_length=30)
role = models.CharField(max_length=10)
address = models.CharField(max_length=50)
email = models.EmailField() # email field doesn't need max_length
password = models.CharField(max_length=20)
phone = models.CharField(max_length=30) # this should be a CharField
GPA = models.FloatField()
gender = models.CharField(max_length=1,
choices=(('M', 'Male',),
('F', 'Female',),
('X', 'Prefer not to disclose',)))
Related
I'm adding TokenAuthentication to our django project. All was going well, and I've added a migration and unit test for the token auth:
# Migration
from django.db import migrations
def create_missing_tokens(apps, schema_editor):
"""
Tokens were added in 0002_auto_20160226_1747, we thus need to populate
the tokens table for existing users
"""
Token = apps.get_model('authtoken', 'Token')
User = apps.get_model('accounts', 'CustomUser')
for user in User.objects.all():
Token.objects.get_or_create(user=user)
class Migration(migrations.Migration):
dependencies = [
# depends on authtoken migration
('accounts', '0003_subscription_max_updates_per_day'),
('authtoken', '0002_auto_20160226_1747'), # latest migration in the authtoken package
]
operations = [
migrations.RunPython(create_missing_tokens, reverse_code=migrations.RunPython.noop),
]
# unit test
class MigrationTestCase(TransactionTestCase):
'''A Test case for testing migrations'''
# These must be defined by subclasses.
migrate_from = None
migrate_to = None
def setUp(self):
super(MigrationTestCase, self).setUp()
self.executor = MigrationExecutor(connection)
self.executor.migrate(self.migrate_from)
def migrate_to_dest(self):
self.executor.loader.build_graph() # reload.
self.executor.migrate(self.migrate_to)
#property
def old_apps(self):
return self.executor.loader.project_state(self.migrate_from).apps
#property
def new_apps(self):
return self.executor.loader.project_state(self.migrate_to).apps
from accounts.models import CustomUserManager
class SummaryTestCase(MigrationTestCase):
"""
We need to test that data is populated in the summary field on running the migration
"""
migrate_from = [('accounts', '0003_subscription_max_updates_per_day')]
migrate_to = [('accounts', '0004_create_tokens')]
def setup_before_migration(self):
manager = CustomUserManager()
User = self.old_apps.get_model('accounts', 'CustomUser')
manager.model = User
manager.create_user(email='contact#a.fr', # nosec
password='kjnfrkj',
)
def test_token_populated(self):
# runs setup
self.setup_before_migration()
# now migrate
self.migrate_to_dest()
# grab new models
Token = self.new_apps.get_model('authtoken', 'Token')
User = self.new_apps.get_model('accounts', 'CustomUser')
for user in User.objects.all():
self.assertTrue(Token.objects.filter(user_id=user.pk).exists())
This works great, but when i actually run the migration i get the message:
django.db.utils.IntegrityError: duplicate key value violates unique
constraint "authtoken_token_pkey" DETAIL: Key (key)=() already
exists.
Here is some pseudo code for what i mean by "actually run the migration":
$ git checkout <old commit> # grab old commit
$ ./run.sh go # spin up docker with server and db
$ git checkout master # which includes migrations
$ ./run.sh again # log into docker image with django
$ (docker) python manage.py migrate # run the migrations
the error i see is thus (full stack trace at the end of the question):
django.db.utils.IntegrityError: duplicate key value violates unique constraint "authtoken_token_pkey"
DETAIL: Key (key)=() already exists.
I cant understand how with a migration that uses Token.objects.get_or_create(user=user) I'm getting a duplicate key? any help would be greatly appreciated
Applying accounts.0004_create_tokens...Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 538, in get_or_create
return self.get(**kwargs), False
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
__fake__.DoesNotExist: Token matching query does not exist.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "authtoken_token_pkey"
DETAIL: Key (key)=() already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle
fake_initial=fake_initial,
File "/usr/local/lib/python3.6/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 "/usr/local/lib/python3.6/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 "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
self.code(from_state.apps, schema_editor)
File "/code/accounts/migrations/0004_create_tokens.py", line 12, in create_missing_tokens
Token.objects.get_or_create(user=user)
File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 541, in get_or_create
return self._create_object_from_params(kwargs, params)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 583, in _create_object_from_params
raise e
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 575, in _create_object_from_params
obj = self.create(**params)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1335, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "authtoken_token_pkey"
DETAIL: Key (key)=() already exists.
EDIT: Custom user class is nothing special, looks like this:
class CustomUser(AbstractUser):
"""
Replace username by email as required and unique.
"""
is_alphanumeric_or_dash = RegexValidator(r'^[0-9a-zA-Z\-]*$', 'Only alphanumeric and "-" characters are allowed.')
# Hide username
username = None
# Overidde other fields
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'),
max_length=100,
blank=True,
validators=[is_alphanumeric_or_dash])
last_name = models.CharField(_('last name'),
max_length=100,
blank=True,
validators=[is_alphanumeric_or_dash])
# /!\ At some point, user should have a default subcription /!\
subscription = models.ForeignKey(Subscription, on_delete=models.PROTECT, blank=True, null=True)
# some other fields, but nothing special...
USERNAME_FIELD = 'email'
# Override the UserManager with our custom one (for objects creation)
objects = CustomUserManager()
A Token's key is normally generated by its save() method. This is fine when you're generating the tokens manually but in a migration, where you're referencing the model via apps.get_model(), none of the custom model methods are available.
So what's happening is that the tokens are being generated with empty keys. The first one will work but all after that will generate this error because the key is not unique.
A simple workaround is to just copy the code that DRF uses to generate the key into your migration. Something like this should work:
for user in User.objects.using(db_alias).all():
key = binascii.hexlify(os.urandom(20)).decode()
Token.objects.using(db_alias).get_or_create(user=user, key=key)
I am very new to django(version 1.11).I am trying to make a shoppingwebsite and i am confused in creating Order model.
In here you can see my first (version 1) models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.postgres.fields import ArrayField
class Products(models.Model):
name = models.CharField(max_length = 20 , default='')
description = models.CharField(max_length = 100 , default='')
price = models.IntegerField(default=0)
image = models.ImageField(upload_to='product_image',blank=True)
vojood = models.BooleanField(default=False)
unique = models.CharField(max_length = 100 ,default='')
typ = models.CharField(max_length = 100 ,default='')
def __str__ (self):
return self.name
#classmethod
def turn_on(prds,pk):
prds[pk].vojood=true
#classmethod
def turn_off(prds,pk):
prds[pk].vojood=false
class Order(models.Model):
username = models.CharField(max_length = 300 , default='')
address = models.CharField(max_length = 300 , default='')
time = models.IntegerField(default=0)
price = models.IntegerField(default=0)
arrived = models.BooleanField(default=False)
basket = ArrayField(models.CharField(max_length=300,default=''),default=list)
def __str__ (self):
return self.username
After python manage.py makemigrations when i tried to migrate the new field (arrayfield) with python manage.py migrate i got a very long error . So the last line was django.db.utils.OperationalError: near "[]": syntax errorSo i deleted the new field(arrayfield) and again i used makemigrations but the error during migrate did not change.And now i cant migrate any field with any type!
And here is my Error :
E:\django projects\4\third>python manage.py makemigrations
Migrations for 'shop':
shop\migrations\0013_auto_20180611_1518.py
- Alter field basket on order
E:\django projects\4\third>python manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, sessions, shop
Running migrations:
Applying shop.0005_order_prds...Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 63, in
execute
return self.cursor.execute(sql)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line
326, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: near "[]": syntax error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
364, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 283,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 330,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py
", line 204, in handle
fake_initial=fake_initial,
File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 11
5, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i
nitial=fake_initial)
File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 14
5, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
initial)
File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 24
4, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 1
29, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py"
, line 87, in database_forwards
field,
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 238, in add_field
self._remake_table(model, create_field=field)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 198, in _remake_table
self.create_model(temp_model)
File "C:\Python34\lib\site-packages\django\db\backends\base\schema.py", line 3
03, in create_model
self.execute(sql, params or None)
File "C:\Python34\lib\site-packages\django\db\backends\base\schema.py", line 1
20, in execute
cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 80, in
execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in
execute
return self.cursor.execute(sql, params)
File "C:\Python34\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 63, in
execute
return self.cursor.execute(sql)
File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line
326, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: near "[]": syntax error
E:\django projects\4\third>
I also changed the name of array field from prds to basket but you can see in the error the name did not change !!!!! And it runs 0005_order_prds despite the last created migration is 00013_etc !
I think your problem is that you are using a SQLite database, you need to use a Postgres database - see this similar question.
I'm designing an Application where username will be an AutoIntegerField and unique.
Here's my model.
class ModelA(models.Model):
username = models.BigAutoField(primary_key=True, db_index=False)
user_id = models.UUIDField(default=uuid.uuid4, unique=True,
editable=False)
Initially, I wanted user_id to be a primary_key, but I can't create an AutoField which is not primary_key. As a result, I'd to let go off user_id as primary_key and assigned username as the primary key.
Now, when I run the migrations, it throws an error saying,
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
Complete StackTrace:-
Applying users.0005_auto_20180626_0914...Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
params,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
I think the issue is that you still have an old index on your username field that clashes with the new type. The db_index=False argument has no effect because primary_key=True always generates an index.
You might be able to solve this by removing primary_key=True, creating a migration, and then re-adding it and creating another migration. Alternatively, you can do it by hand by dropping and re-creating the index. If you want to go down that path, consult this answer.
If your project is still in an early stage and you don't have any valuable data, you can take the easy way out and drop any tables related to your users app or even the complete database, delete all migrations in the users app and create them from scratch.
in my case I was connecting django to postgres at localhost pgadmin
first deleted all the migrations except default one and also in the pycache
then just run python manage.py makemigrations and python manage.py migrate in your terminal
I first created the User model before I read the Django documentation about authentication so I put all attributes in the same model. So, later I tried to split it into User and User profile. But when I run the the population script, it says User profile table is not found even though I saw the SQL that created it.
These are two classes connected to the User model that I import.
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
profilepic = models.ImageField(blank=True)
city = models.ForeignKey(City)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
#property
def avg_rating(self):
return self.userrating_set.all().aggregate(Avg('rating'))['rating__avg']
class UserRating(models.Model):
user = models.ForeignKey(User)
comment = models.CharField(max_length=500)
for_username = models.CharField(max_length=128)
rating = models.IntegerField(default=5)
def __unicode__(self):
return unicode(self.rating)
And this is the portion of the population script where the problem is:
new_user = User.objects.get_or_create(username=username, email=email)[0]
#new_user.profilepic = profile_picture
new_user.firstname = first_name
new_user.secondname = last_name
new_user.save()
new_user_profile = UserProfile.objects.get_or_create(user=new_user, city=created_city)
new_user_profile.slug = username
new_user_profile.save()
And this is the error I get when running the script:
Traceback (most recent call last):
File "C:\Users\bnbih\app_name\populationScript.py", line 108, in <module>
populate()
File "C:\Users\bnbih\app_name\populationScript.py", line 101, in populate
new_user_profile = UserProfile.objects.get_or_create()
File "C:\python27\lib\site-packages\django\db\models\manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\python27\lib\site-packages\django\db\models\query.py", line 422, in get_or_create
return self.get(**lookup), False
File "C:\python27\lib\site-packages\django\db\models\query.py", line 351, in get
num = len(clone)
File "C:\python27\lib\site-packages\django\db\models\query.py", line 122, in __len__
self._fetch_all()
File "C:\python27\lib\site-packages\django\db\models\query.py", line 966, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\python27\lib\site-packages\django\db\models\query.py", line 265, in iterator
for row in compiler.results_iter():
File "C:\python27\lib\site-packages\django\db\models\sql\compiler.py", line 700, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\python27\lib\site-packages\django\db\models\sql\compiler.py", line 786, in execute_sql
[Finished in 0.8s with exit code 1]cursor.execute(sql, params)
File "C:\python27\lib\site-packages\django\db\backends\utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 485, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: mainapp_userprofile
Django's sqlmigrate just shows you what will get run, it doesn't apply any changes, you need to run migrate
Prints the SQL for the named migration. This requires an active database connection, which it will use to resolve constraint names; this means you must generate the SQL against a copy of the database you wish to later apply it on.
I have been reading tango_with_django tutorial, and when I managed to get to part 7, I was stucked.
When I added this code
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
I've got this
Traceback (most recent call last): File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line
utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 338, in execute
output = self.handle(*args, **options) File "C:\Python34\lib\site-packages\django\core\management\commands\migrate.py ", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False)) File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 68 , in migrate
self.apply_migration(migration, fake=fake) File "C:\Python34\lib\site-packages\django\db\migrations\executor.py", line 10 2, in apply_migration
migration.apply(project_state, schema_editor) File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 1 08, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, ne w_state) File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py" , line 37, in database_forwards
field, File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\schema.py", lin e 176, in add_field
self._remake_table(model, create_fields=[field]) File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\schema.py", lin e 144, in _remake_table
self.quote_name(model._meta.db_table), File "C:\Python34\lib\site-packages\django\db\backends\schema.py", line 102, i n execute
cursor.execute(sql, params) File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params) File "C:\Python34\lib\site-packages\django\db\utils.py", line 94, in
__exit__
six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python34\lib\site-packages\django\utils\six.py", line 658, in reraise
raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params) File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py", line 485, in execute
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.sl ug
After I removed this code, I still get same error message while trying to do
python manage.py migrate
After I deleted database with
python manage.py flush
And entered
python manage.py migrate
I also got the same error.
What's going on?
try rolling back the migration to the previous state. Assuming this is your first migration - lets roll back to zero
python manage.py migrate category zero
slug logic can get a bit complex
despite names being different they can have the same slug
e.g.
Name: Foo Bar
Slug: foo-bar
Name: foo bar
Slug: foo-bar
Name: Foo Bar
Slug: foo-bar
Name: Foo! Bar
Slug: foo-bar
...you get the idea
you defiantly want unique slugs to make url access nice
e.g. domain.com/category/1234 (using id)
vs domain.com/category/foo-bar
have a look at AutoSlugField which will do lots of the hard work for you in terms of making unique slugs