Preface: I was writing my own Page app that used MPTT and a custom page model. This was working for me, but FlatPages is more refined than my custom Page Model and so I'm leaning toward just extending it.
from django.db import models
from django.contrib.flatpages.models import FlatPage
from mptt.models import MPTTModel
class ExtendedFlatPage(FlatPage, MPTTModel):
parent = models.ForeignKey('ExtendedFlatPage', null=True, blank=True, default=None, related_name="children", help_text="Hierarchical parent page (if any)")
class Meta:
ordering = ['flatpages__url']
order_with_respect_to = 'parent'
verbose_name = 'page'
verbose_name_plural = 'pages'
class MPTTMeta:
left_attr = 'mptt_left'
right_attr = 'mptt_right'
level_attr = 'mptt_level'
order_insertion_by = ['title']
def __unicode__(self):
return self.url
This almost works, except throws an error when I go to run python manage.py syncdb
Error:
iMac:cms colab$ python manage.py syncdb
Creating tables ...
Creating table my_flatpages_extendedflatpage
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/core/management/commands/syncdb.py", line 101, in handle_noargs
cursor.execute(statement)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Django-1.3-py2.7.egg/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build/bdist.macosx-10.6-intel/egg/MySQLdb/cursors.py", line 174, in execute
File "build/bdist.macosx-10.6-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
django.db.utils.DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 2")
If anyone could point me in the right direction, I would greatly appreciate it. Thanks!
replace
class ExtendedFlatPage(FlatPage, MPTTModel):
with
class ExtendedFlatPage(MPTTModel, FlatPage):
This will allow MPTTModel class to override FlatPage attributes and methods.
#comment
It appears that something (an attribute, method) in FlatPage model overrides something in MPTTModel cousing this error.
order of classes you import from is important. here's an example:
class A:
attribute = 1
class B:
attribute = 2
class C(A,B):
pass
class C attribute value will be 1.
Related
im just stuck with error while making migrations to my django project.
in my project which is already 50% dveloped i use owner model to represent owner of shop and then i used user model for login and for registration purpose.
so i tried to use user model in my owner model so i could utilise both model effectively with additional fields.
i tried to extend user model in owner model using onetoone field.
after doing that i was not able to do migrations so i deleted all migrations files but after that it was start giving this error while doing migrations:-
py manage.py makemigrations
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 "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 369, in execute
output = self.handle(*args, **options)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
self.build_graph()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph
raise exc
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph
self.graph.validate_consistency()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp>
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
django.db.migrations.exceptions.NodeNotFoundError: Migration listings.0001_initial dependencies reference nonexistent parent node ('owners', '0001_initial')
here is my Owner Model :-
from django.db import models
from django.contrib.auth.models import User
class Owner(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, default=False)
name=models.CharField(max_length=200)
photo=models.ImageField(upload_to='photos/%Y/%m/%d/')
description=models.TextField(blank=True)
phone=models.CharField(max_length=20)
email=models.CharField(max_length=20)
def __str__(self):
return self.name
im hoping that will get help on this because i'm totally stuck here and also not getting how to tackle this problem.
You are using the term "migration folder of my django project" (in a comment above), and that is wrong -- each app in your project has its own migration folder. Specifically, there is still a migration in your "listings" app, and it lists as a dependency one of the migrations you deleted.
after reviewing and debugging that stack trace i finally get rid of that problem.
i delete the migration file 0001 from my listing app which was having relationship with Owner Model and then when i run makemigrations command it didn't given me any error or exception like i mentioned above.
When attempting to migrate my database in Django. I receive the following:
Running migrations:
Applying shop.0002_transactions...Traceback (most recent call last):
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 942, in contribute_translations
base = shared_model._parler_meta
AttributeError: type object 'Product' has no attribute '_parler_meta'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle
fake_initial=fake_initial,
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/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 "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/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 "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/migration.py", line 114, in apply
operation.state_forwards(self.app_label, project_state)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 86, in state_forwards
list(self.managers),
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 96, in add_model
self.reload_model(app_label, model_name)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 157, in reload_model
self._reload(related_models)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 190, in _reload
self.apps.render_multiple(states_to_be_rendered)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 307, in render_multiple
model.render(self)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 578, in render
return type(self.name, bases, body)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/base.py", line 320, in __new__
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/migrations/state.py", line 338, in register_model
self.do_pending_operations(model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 424, in do_pending_operations
function(model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 403, in apply_next_model
self.lazy_model_operation(next_function, *more_models)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/apps/registry.py", line 389, in lazy_model_operation
function()
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/fields/related.py", line 317, in resolve_related_class
field.do_related_class(related, model)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/django/db/models/fields/related.py", line 388, in do_related_class
self.contribute_to_related_class(other, self.remote_field)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/fields.py", line 58, in contribute_to_related_class
self.model.contribute_translations(cls)
File "/Users/itsd/Desktop/Web Projects/Django Projects/e-commerce_shop/env/myshop/lib/python3.7/site-packages/parler/models.py", line 944, in contribute_translations
raise TypeError("Translatable model {} does not appear to inherit from TranslatableModel".format(shared_model))
TypeError: Translatable model <class '__fake__.Product'> does not appear to inherit from TranslatableModel
I do not understand what the issue is preventing me from migrating the database.
Any help is appreciated.
My models.py file
from django.db import models
from django.urls import reverse
from parler.models import TranslatableModel, TranslatedFields
class Category(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=200, db_index=True),
slug = models.SlugField(max_length=200, db_index=True,
unique=True)
)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category', args=[self.slug])
class Product(TranslatableModel):
translations = TranslatedFields(name = models.CharField(max_length=200,
db_index=True), slug = models.SlugField(max_length=200, db_index=True),
description = models.TextField(blank=True))
category = models.ForeignKey(Category, related_name='products',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.id, self.slug])
I do not understand what the issue may be. Here is my admin.py also. I believe the disconnect is between these two files after I make migrations and attempt to migrate.
from django.contrib import admin
from .models import Category, Product
from parler.admin import TranslatableAdmin
#admin.register(Category)
class CategoryAdmin(TranslatableAdmin):
list_display = ['name', 'slug']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
#admin.register(Product)
class ProductAdmin(TranslatableAdmin):
list_display = ['name', 'slug', 'price', 'available', 'created',
'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'available']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
I think the solution to this problem is in the same book you are working from.
Have you read this and made sure you changed the two occurences, not only one?
Edit the file migrations/0002_translations.py of the shop application and replace the two occurrences of the following line:
Copy
bases=(parler.models.TranslatedFieldsModelMixin, models.Model),
with the following one:
Copy
bases=(parler.models.TranslatableModel, models.Model),
This is a fix for a minor issue found in the django-parler version you are using. This change is necessary to prevent the migration from failing when applying it. This issue is related to creating translations for existing fields in the model and will probably be fixed in newer django-parler versions.
As far as I could see, the answer is that "parler" is currently broken. I ran into the same problem as you and even though I also tried to follow the documentation (and NOT the book!) at django-parler.readthedocs.io, the result was a COMPLETELY destroyed set of migrations, which I then had to painfully delete and rebuilt from scratch (always make complete backups BEFORE you do anything that touches migrations!).
I have opened a case with the Django Parler team #GitHub, but I have so far not received any answer. I believe this product is no longer maintained, or they have too many other things to work on.
In the end I ignored anything that used "Django-parler" in the book and jumped to the next section.
Once I will be working on my own product, I will most likely have to try other solutions from djangopackages.org
I know this is not the solution you were looking for, but I believe it is the correct answer, since "parler" simply seems to be broken at this point in time.
I encountered a strange behavior while applying a signal to a new model, I'm not sure to understand what is wrong but it seems related with the fact that I used abstract classes.
The models (simplified)
Basically, I have Article, Photo (inheriting from Post)
class Post(models.Model):
class Meta:
abstract = True
some_field = models.Something()
class Article(Post):
category = models.ForeignKey(Article_category, null=True, on_delete=models.SET_NULL)
some_field = models.Something()
class Photo(Post):
category = models.ForeignKey(Photo_category, null=True, on_delete=models.SET_NULL)
some_field = models.Something()
and their respective Categories
class Category(models.Model):
class Meta:
abstract = True
parent = models.ForeignKey('self', null=True, blank=True, related_name='nested_category', on_delete=models.SET_NULL)
name = models.CharField(max_length=50)
count = models.PositiveSmallIntegerField(default=0, editable=False)
class Article_category(Category):
#classmethod
def load(cls):
cache.set('{}'.format(cls.__name__), cls.objects.all())
class Photo_category(Category):
#classmethod
def load(cls):
cache.set('{}'.format(cls.__name__), cls.objects.all())
The signal
A straighforward incremental counter. Every time an article/photo is created, it's corresponding category count is updated and the entire model is saved in the cache (for templating purposes)
from django.db.models import F
#receiver(post_save, sender=Article) ----> here comes trouble
#receiver(post_save, sender=Photo)
def add_one_to_count(sender, instance, **kwargs):
cat = type(instance.category).objects.get(name=instance.category)
cat.count = F('count')+1
cat.save()
cache.set('{}_category'.format(sender.__name__), type(instance.category).objects.all())
The problem
What you saw above works like a charm for #receiver(post_save, sender=Photo) but when I add #receiver(post_save, sender=Article), DB initialization with fixture fails and I only get emptyset tables (mariaDB). This very line is the only one changing fail to success and I can't figure why. Since count is defined in the abstract class, I wondered whether it had something to do with it, for I did not have any issue applying a similar logic to categories:
# this works perfectly
#receiver(post_save, sender=Photo_category)
#receiver(post_delete, sender=Photo_category)
#receiver(post_save, sender=Article_category)
#receiver(post_delete, sender=Article_category)
def refresh_cached_category(sender, instance, using, **kwargs):
cache.set('{}'.format(type(instance).__name__), type(instance).objects.all())
Thanks for any enlightenment
The complete Traceback
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 "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/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.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
self.loaddata(fixture_labels)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata
self.load_label(fixture_label)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label
obj.save(using=self.using)
File "/usr/local/lib/python3.7/site-packages/django/core/serializers/base.py", line 223, in save
models.Model.save_base(self.object, using=using, raw=True, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 790, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "/usr/src/cms/website/observers.py", line 26, in add_one_to_count
cat = type(instance.category).objects.get(name=instance.category)
File "/usr/local/lib/python3.7/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.7/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
website.models.DoesNotExist: Problem installing fixture '/usr/src/cms/../test/data_dev.yaml': Article_category matching query does not exist.
You can't filter on name=instance.category in your query, because that's not a str. You need to filter on name=instance.category.name but first you also need to make sure instance.category isn't None (since it can be).
The thing I don't understand is why you perform a query in the first place, just to fetch the same object: instance.category is the same as ArticleCategory.objects.get(name=instance.category.name) assuming the name is unique, except you do an extra query to the db.
Also the query will raise an exception if you have two categories with the same name (which you don't exclude in your model). So your code should be:
def add_one_to_count(sender, instance, **kwargs):
if instance.category:
instance.category.count = F('count')+1
instance.category.save()
cache.set('{}_category'.format(sender.__name__), type(instance.category).objects.all())
I'm getting an error when running a migration changing a field from a CharField to a ManyToMany field.
I have a custom user model which chooses their interests, which I have greatly reduced for simplicity's sake.
# main.models
class Interest(models.Model):
"""
get what the user is interested in.
"""
name = models.CharField(max_length=30)
def __str__(self):
return self.name
# accounts.models
from main.models import Interest
class User(AbstractUser):
"""
the custom user class we are using
"""
# before it was:
# interests = models.CharField(max_length=100, blank=True)
interests = models.ManyToManyField(Interest, blank=True, null=True,
help_text="What are your interests or hobbies?")
# migration.py
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_remove_user_friends'),
]
operations = [
migrations.AlterField(
model_name='user',
name='interests',
field=models.ManyToManyField(help_text='What are your interests or hobbies?', to='main.Interest', null=True, blank=True),
preserve_default=True,
),
]
The main app is installed correctly in INSTALLED_APPS, the dependencies are there, and I haven't had any migration problems up until now (9th migration within the accounts app).
Here is the stack trace. It appears it is having problems with to='main.Interest' in the migration file, but I'm not sure how to go about fixing that?
Applying accounts.0010_auto_20150309_1554...Traceback (most recent call last):
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/apps/registry.py", line 148, in get_app_config
return self.app_configs[app_label]
KeyError: 'main'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/db/migrations/state.py", line 84, in render
model = self.apps.get_model(lookup_model[0], lookup_model[1])
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/apps/registry.py", line 202, in get_model
return self.get_app_config(app_label).get_model(model_name.lower())
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/apps/registry.py", line 150, in get_app_config
raise LookupError("No installed app with label '%s'." % app_label)
LookupError: No installed app with label 'main'.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/db/migrations/executor.py", line 68, in migrate
self.apply_migration(migration, fake=fake)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/db/migrations/executor.py", line 96, in apply_migration
if self.detect_soft_applied(migration):
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/db/migrations/executor.py", line 140, in detect_soft_applied
apps = project_state.render()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/db/migrations/state.py", line 94, in render
raise ValueError(msg.format(field=operations[0][1], model=lookup_model))
ValueError: Lookup failed for model referenced by field accounts.User.interests: main.Interest
I am working on a Django web app with south for db migration. I am quite new to south, and django as well. I tried using south with the official tutorials, however it failed with an exception: AttributeError: 'Options' object has no attribute 'index_together'.
I run the south command like this:
python manage.py schemamigration southtut --initial
The southtut models is this:
class Knight(models.Model):
name = models.CharField(max_length=100)
of_the_round_table = models.BooleanField()
My project models is this:
class Author(models.Model):
name = models.CharField(max_length=64)
authorId = models.CharField(max_length=32)
def __unicode__(self):
return self.name
class Meta:
db_table="Author"
class Video(models.Model):
videoId = models.CharField(max_length=32)
videoUrl = models.URLField(max_length=200)
author = models.ForeignKey(Author, null=True, related_name="videos", on_delete=models.SET_NULL)
class Meta:
db_table="Video"
class User(models.Model):
token = models.CharField(max_length=50, null=True)
favs = models.ManyToManyField(Video, related_name="fans", db_table="VideoUserR")
class Meta:
db_table = "User"
The whole error message I got is as below:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/management/commands/schemamigration.py", line 151, in handle
for action_name, params in change_source.get_changes():
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/changes.py", line 460, in get_changes
model_defs = freeze_apps([self.migrations.app_label()])
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/freezer.py", line 37, in freeze_apps
model_defs[model_key(model)] = prep_for_freeze(model)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/creator/freezer.py", line 78, in prep_for_freeze
fields['Meta'] = remove_useless_meta(modelsinspector.get_model_meta(model))
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/modelsinspector.py", line 441, in get_model_meta
meta_def[kwd] = get_value(model._meta, defn)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/modelsinspector.py", line 258, in get_value
value = get_attribute(field, attrname)
File "/Library/Python/2.7/site-packages/South-0.7.6-py2.7.egg/south/utils/__init__.py", line 38, in get_attribute
value = getattr(value, part)
AttributeError: 'Options' object has no attribute 'index_together'
Thanks
It's bug in south 0.8. Just update to 0.8.1 or newer and all be good.
It looks like this is because you are trying to use index_together option in Meta section of your model. But this option is available only for django 1.5+ and i guess that you run it on a less recent version of django.
I updated my django to 1.5.1, and this error disappeared. I have no idea how the 'index_together' come out, but since it is available in django 1.5.1, it get what it needs.