I am using Django 1.8b1
There are two models in two apps called accounts and products
products/models.py
class ChecklistEnterpriseType(models.Model):
checklist_enterprise_type = models.CharField('Type of Enterprise', max_length=50, choices=zip(ENTERPRISE_CHOICES, ENTERPRISE_CHOICES))
def __unicode__(self):
return self.checklist_enterprise_typ
And the another model is
accounts/models.py
class sample(models.Model):
enterprise_type = models.ForeignKey(ChecklistEnterpriseType, related_name='enterprise_type')
def __unicode__(self):
return self.enterprise_type
When I do python manage.py makemigrations, it will add the migration file. But when I do python manage.py migrate it raises me the error like:
raise ValueError('Related model %r cannot be resolved' % self.rel.to)
ValueError: Related model u'products.ChecklistEnterpriseType' cannot be resolved
How can I resolve this.
Appreciated the answers :)
A very delayed response... but I just had a similar issue that was very hard to track down, but eventually did, so am putting a pointer here in case anyone else gets hit by it. I was adding testing to a several year old Django webapp, and found that ./manage.py test was failing. I had never run ./manage.py migrate on an empty database!
At some stage in the early days of Django 1.7 migrations were generated that had failed circular dependency detection, so you could update from a newer version but not the first migrations. See https://code.djangoproject.com/ticket/22319 for the bug report.
I still had to work out how to fix it without throwing away all my migrations and generating them fresh.
So to fix, I went through all the migrations (it was only 5 affected files). Some models were required by earlier migrations, but they weren't included due to individual fields depending on later migrations. So I brought the whole migrations.CreateModel for the model back to an earlier migration, but took those fields and used migrations.AddField in the later migration (where the model had been put originally).
Hopefully that explains it, but if anyone runs into this issue sometime in the future, feel free to comment if it needs further elaboration.
I think this line:
checklist_enterprise_type = models.CharField('Type of Enterprise', max_length=50, choices=zip(ENTERPRISE_CHOICES, ENTERPRISE_CHOICES))
Should Be:
checklist_enterprise_type = models.CharField(verbose_name='Type of Enterprise', max_length=50, choices=zip(ENTERPRISE_CHOICES, ENTERPRISE_CHOICES))
Related
I have a big Django application, currently trying to upgrade from 1.6 to 1.7 (there's been attempts to upgrade straight to 1.11, but it was too much trouble, so my plan is to do it one minor at a time).
I'm following the Upgrade from South instructions, and deleted all previous migrations, but I can't get makemigrations to work. The current problem is that the auth.User model has been patched to include two new fields:
User.add_to_class('profile',
models.ForeignKey('access.Profile', null=True, blank=True,
related_name='user_foreignkey'))
User.add_to_class('profiles',
models.ManyToManyField('access.Profile', null=True,
blank=True))
This patch was made in a separate app. If I just leave it where it is, I get the following error when running python manage.py makemigrations:
ValueError: Lookup failed for model referenced by field auth.User.profiles:
access.Profiles
I tried moving the add_to_class calls to the same file where Profile is defined, (after the definition), but got the same error. I also tried changing the syntax from 'access.Profile' to Profile, to no effect. Is there something else that could make this work?
If not, since I'm adding fields to the model, I figure the correct approach would be extend the AbstractUser model, as suggested by this guide. The problem with this is that the new initial migration will create a table access_user instead of using the existing auth_user. Would it be safe to simply rename auth_user to access_user and fake the migration?
Any other suggestions on how to overcome this with the least refactoring possible (management always thinks there are more urgent things than the upgrade) are welcome.
tl, dr; I removed auth migrations and ran makemigrations again, that seems to have solved the problem.
I had decided to give option 2 a try. I removed the add_to_class patches, created a new class User(AbstractUser) with the new fields, removed all the existing migrations and ran makemigrations again. I got the exact same error, which made no sense because there was no longer any code relating auth.User to Profile, so I decided to investigate auth migrations. I ran
$ python migrate --list settings=settings.mysettings
and it showed a suspicious migration for auth, with yesterday's date, probably when I first tried to make migrations.
Tutorials on "how to reset all migrations" do not mention third-party installed apps, but thanks to this thread I knew where Django stored the auth migrations, so I removed both of them (the initial and the suspicious one) and reordered the INSTALLED_APPS so that access is now before django.contrib.auth. Then ran makemigrations again, and it got through access and auth migrations successfully.
I'm now getting other problems with migrations in other apps, but they don't seem to be related with this.
It might be nice to have a more intuitive way to reset all existing migrations, not only those from your repo. But then again, I don't think the add_to_class patches are the proper way to do what we wanted.
I am working on an existing Django project that contains migration code like:
someFluffyModel.objects.all().delete()
or
someModel = SomeModel(....)
someModel.save()
Now wherever there is such code and newer migrations change the schema that reflect the current version of the model, there is an issue in applying migrations from scratch.
As I understand the reason is that the model used in the migration doesn't reflect the model used in the migration at that point in time. As I have found fixtures can help in loading data but how about deletion?
Is the preferred way to manually delete data from the database?
Sorry forgot to answer my own old question it's been years now but just in case anybody is curious in your migrations you should always be using historical models. The reason is that you get the model at a point in time(reconstructed incrementally base on schema migrations).
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Country = apps.get_model("myapp", "Country")
This way if you try to re-run your migrations at some point in the future with model schema x'' old migrations will be run using x' and x depending on their dependencies.
Avoid importing models to your migrations directly at any cost.
It is always important to be able to rer-run you migrations since that allows you to migrate forwards backwards between your environments roll back faulty deployments and above all run your tests. If you are doing it wrong your tests will fail at some point when you'll get to schema x' and you'll have to follow the correct approach mentioned above to fix them.
Thanks to #Daniel Roseman for giving me some pointers that day.
I'm going through and checking the various pages in our project, and the great majority appear to be working fine after the upgrade. However, when I try to view a particular entry in the admin, I get this error. On viewing the stack trace, everything is being done internally within Django's admin code, so there is no place in my own code that I can go to debug. This would suggest either that there is something wrong with the Django admin or that there is some release note I missed that is necessary to make this work properly. Any ideas? The actual error is happening here:
site-packages/django/contrib/admin/helpers.py in contents, line 206
if isinstance(f.rel, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f)
Obviously, I could go into Django and hack around, but I shouldn't have to do this on a new installation. Any help on pinpointing the issue would be much appreciated. I'm just staring t the screen at this point.
Was responding to Alasdair's comment and got to playing with our admin code, and I was able to narrow it down to the method call that was causing the error.
We have a Lead model that relates to our Company model via a ManyToManyField (i.e. one lead can be for one or more companies). The field that relates Lead to Company has a related_name of "leads".
class Company(models.Model):
...
class Lead(models.Model):
companies = models.ManyToManyField(Company, blank=True, related_name='leads')
...
The CompanyAdmin, looks like the following:
class CompanyAdmin(admin.ModelAdmin):
...
readonly_fields = 'leads',
...
def leads(self, obj):
...
So what appears to have been happening was, when we were trying to access the leads method from CompanyAdmin, Django was instead trying to access the company's Lead objects via the related name -- the ManyToManyField that was throwing the error. I resolved the conflict by changing the method name in the admin to "my_leads".
Looks like something was changed somewhere between 1.8 and the final version of 1.6 that has opened the door to potential conflict between related names and admin methods. The solution, make sure there is no overlap in naming, and things should work fine.
I am trying to add two additional profile fields and have the native authentication work like normal.
I am trying to fallow the documentation here
and the SO here
In my settings file
#settings.py
AUTH_USER_MODEL = 'users.User'
in my users.user model
#users/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
foo = models.CharField(max_length=32, default='Blue')
bar = models.CharField(max_length=32, default='Blue')
print "user.user"
i have created 3 superusers non can log into admin. i have tried syncing the DB after adding a user. i have tried restating the dev server between adding a user.
the only time i see the output of print "user.user" is when i run the createsuperuser command.
i think i cant log in because the user is not really being created. it runs my User class and then skips actually creating the user. but i am kinda new to this so i could be way off and way out of my league.
why cant i log in and how do i add the two fields?
Have you read the warning in Django's documentation?
Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before running manage.py syncdb for the first time.
If you have an existing project and you want to migrate to using a custom User model, you may need to look into using a migration tool like South to ease the transition.
Given this warning, are you working on a fresh database, or are you migrating using South? If you have an existing database and made these changes, then simply running syncdb will most likely no be sufficient.
If this is a development server without any important data, I would recreate your database, and then run ./manage.py syncdb. If you are using a SQLite database, then you can simply copy it to somewhere else (if you would like to keep the data), and run syncdb again to create a new database.
Here is the relevant documentation.
It would also be helpful to know exactly what error you are receiving. Do you attempt to login and admin tells you that your user/pass combination is not correct, or is there an actual error thrown? Your question doesn't quite make this clear.
I've been battling with this issue for several hours now and I'm at a loss. I'm adding a ForeignKey model reference to an existing model and then trying to run a migration with South:
class Existing(models.Model):
existing_type = models.ForeignKey(ExistingType)
new_model = models.ForeignKey(NewModel, default=None, blank=True)
def __unicode__(self):
return self.existing_type.name
When I try and run manage.py schemamigation [app] --auto I get the following:
DatabaseError: (1054, "Unknown column 'core_existing.new_model_id' in 'field list'")
I've tried to manually create a migration file, but when I run it I get the same error message. Its almost as if some internal django process is preventing south from running as the models don't validate.
I'm aware I could manually update the database to fix this, but this is far from ideal given multiple devs working on this project as well handling this across multiple development environments.
Can anyone provide any insight?
I'm running:
django 1.5.5
south 0.8.4
mysql
EDIT:
Incidentally I cannot add ANY field type to this model, but I am able to create new models via south - if I comment out the additional field