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.
Related
I'm trying to deploy a Django app to Heroku, and the moment I start doing the migrations with these commands:
heroku run python manage.py makemigrations
heroku run python manage.py migrate
I get the following error, here's the full stack trace:
Running migrations:
Applying transaction.0004_auto_20210315_0103...Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.SyntaxError: multiple default values specified for column "id" of table "Transaction"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 245, in handle
fake_initial=fake_initial,
File "/app/.heroku/python/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 "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "/app/.heroku/python/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 "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 106, in database_forwards
field,
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 487, in add_field
self.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 142, in execute
return super().execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "Transaction"
This is the code from my Transaction Model:
class Transaction(models.Model):
"""Modelo de Transaccion"""
id = models.CharField(max_length=8, primary_key = True)
TnType = models.ForeignKey(TransactionType, on_delete=models.CASCADE,
blank=True, null=True,
related_name='id_tn_type')
userReceiver = models.ForeignKey(User,on_delete=models.CASCADE,
related_name='user_receiver', blank=True, null=True)
userTransmitter = models.ForeignKey(User,on_delete=models.CASCADE,
related_name='user_transmitter', blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
creationTime = models.DateTimeField(default=datetime.now)
concept = models.CharField(max_length=80, blank=True, null=True)
STATUS = (
('A','Active'),
('I','Inactive'),
)
status = models.CharField(max_length=1,choices=STATUS, default='A')
def __str__(self):
return self.id
class Meta:
db_table = "Transaction"
class TransactionAdmin(admin.ModelAdmin):
list_display = ('id', 'userReceiver', 'userTransmitter', 'amount' )
I really don't understand this error, I've been trying a lot of things with no luck. I hope someone could help.
This is my: 0004_auto_20210315_0103
class Migration(migrations.Migration):
dependencies = [
('transaction', '0003_auto_20210315_0101'),
]
operations = [
migrations.RemoveField(
model_name='transaction',
name='idTransaction',
),
migrations.AddField(
model_name='transaction',
name='id',
field=models.AutoField(auto_created=True, default='1', primary_key=True, serialize=False, verbose_name='ID'),
preserve_default=False,
),
]
I have been trying this problem for a very long time. But I just cannot seem to find the solution. I am trying to deploy my project on pythonanywhere, where I have chosen MySQL. Whenever I try to migrate my models with python manage.py migrate. I get the following error:
This is my models.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Thing(models.Model):
thing_name = models.CharField(max_length=64, unique=True)
def __str__(self):
return self.hobby_name
class Person(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
)
first_name = models.CharField(max_length=64, null=True, blank=False)
last_name = models.CharField(max_length=64, null=True, blank=False)
hobbies = models.ManyToManyField(Hobby, blank=False)
email = models.EmailField(max_length=64, blank=True, null=True, unique=True)
city = models.CharField(max_length=64, null=True, blank=False)
zip_code = models.CharField(max_length=10, null=True, blank=False)
description = models.TextField(max_length=2048, null=True, blank=True)
gender = models.CharField(max_length=1,
choices=(
('N', 'No answer'),
('M', 'Male'),
('F', 'Female'),
('O', 'Other')
), null=True, blank=True, default="N"
)
bad = models.BooleanField(default=False)
good = models.BooleanField(default=True)
maximum_hours = models.PositiveIntegerField(default=2)
def __str__(self):
try:
string = self.first_name + " " + self.last_name
except:
string = "name_error"
return string
Last note is that I have DROPPED and re-CREATED the database several times. Each time by:
CREATE DATABASE database_name DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
I am deploying all of this to Pythonanywhere.
The model Thing actually becomes a table. But the model Person does not.
Edit: Here is the full traceback
(hobbyin) 01:16 ~/hobbyin (master)$ python manage.py migrate
System check identified some issues:
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It
is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode
Operations to perform:
Apply all migrations: account, admin, auth, contenttypes, external_page, sessions, sites, socialaccount
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying account.0001_initial... OK
Applying account.0002_email_max_length... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying external_page.0001_initial...Traceback (most recent call last):
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query
rowcount = self._do_query(q)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query
db.query(q)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query
_mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')
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 "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/home/maxxie/.virtualenvs/hobbyin/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 "/home/maxxie/.virtualenvs/hobbyin/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 "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/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/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 92, in database_forwards
schema_editor.create_model(model)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 314, in create_model
self.execute(sql, params or None)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 133, in execute
cursor.execute(sql, params)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query
rowcount = self._do_query(q)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query
db.query(q)
File "/home/maxxie/.virtualenvs/hobbyin/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')
Found the answer. When you deploy your code to production. Make sure that your migration files are removed. Otherwise it might cause unexpected errors such as this one.
app.models.py
class ColorSet(models.Model):
color = models.CharField(max_length=50, verbose_name='Color', default='', blank=True, null=True)
code = models.CharField(max_length=50, verbose_name='Code of color', default='', blank=True, null=True)
class Meta:
verbose_name = 'Color'
verbose_name_plural = 'Colors'
Also project.models.py
class Product(models.Model):
title = models.CharField(max_length=200, verbose_name='Title of product')
slug_field = models.SlugField(max_length=50, verbose_name='Slug', default='')
description = models.TextField(verbose_name='Description')
color_set = models.ForeignKey(ColorSet, verbose_name='Color', default='', blank=True, null=True)
def __str__(self):
return '%s %s %s' % (self.title, '->', self.category)
class Meta:
verbose_name = "Product"
verbose_name_plural = "Products"
If I am doing 'migrate', I see something like this
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/home/vladislav/.local/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 "/home/vladislav/.local/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 "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/vladislav/.local/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 "/home/vladislav/.local/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
field,
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 429, in add_field
self.execute(sql, params)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/vladislav/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: column "color_set_id" contains null values
I tried to add 'blank = True, null = True', but it's didn't help me.
How can I fix this problem?
Follow these steps
python manage.py migrate --fake
comment color_set
python manage.py makemigrations && python manage.py migrate
uncomment color_set
python manage.py makemigrations && python manage.py migrate
The problem is because you added null=True after creating the migration file. Follow these steps now.
1) Drop ColorSet & Product tables from your local table database.
2) Delete all the migration files you created for these `CharField to a ForeignKey` change
3) execute `python manage.py makemigrations`
4) execute 'python manage.py migrate'
Initially my model looked something like this:
from __future__ import unicode_literals
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django.db import models
from datetime import datetime
class blogpost(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField()
createdon = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True)
author = models.ForeignKey(User)
I applied makemigrations and then migrate to this model. Now, I wanted to remove the field slug from this model. I removed it and then applied makemigrations.
^C(mysite)shivam#shivam-HP-Pavilion-15-Notebook-PC:~/Python/django/mysite/mysite$ python manage.py makemigrations
Migrations for 'blog':
0003_remove_blogpost_slug.py:
- Remove field slug from blogpost
But now when I apply migrate, it gives me an error.
Operations to perform:
Apply all migrations: admin, blog, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying blog.0003_remove_blogpost_slug...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/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 "/home/shivam/Python/django/mysite/local/lib/python2.7/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 "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 121, in database_forwards
schema_editor.remove_field(from_model, from_model._meta.get_field(self.name))
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 438, in remove_field
self.execute(sql)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 110, in execute
cursor.execute(sql, params)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 112, in execute
return self.cursor.execute(query, args)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/shivam/Python/django/mysite/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1091, "Can't DROP 'slug'; check that column/key exists")
What should I do to remove the slug field?
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