Reputation: 187
I have a Django project called myoffice. In this project I created an app proposals. Before creating this I had performed makemigrations and migrate creating auth_user table and other tables like auth_user_groups etc.
After creating proposals app, it was working fine.
Now I created a new app called expenses. I have written all models, views, templates and url files. In my models, a couple of models have foreign key reference to users like this:
exch_usr = models.ForeignKey('User', on_delete=models.PROTECT)
I have imported user model as below:
from django.contrib.auth.models import User
Yet, I am getting an error while running makemigrations:
ValueError: Cannot create form field for 'txn_usr' yet, because its related model 'User' has not been loaded yet
Upvotes: 0
Views: 142
Reputation: 377
The @danielr 's answer is perfect but I have a recommendation for you @Parry. So if the User model might be swapped out for another(thinking in the future) and to make your application as reusable as possible you should use the settings.AUTH_USER_MODEL as a references in your models . More information on customizing and referencing the User model can be found at https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#referencing-the-user-model. And inside your code you must use the get_user_model Django(to create User references ) utility to create this switch in a clean way.
class SomeClass(models.Model):
....
custome_user = models.ForeignKey(settings.AUTH_USER_MODEL)
and to make references to User properties:
from django.contrib.auth import get_user_model
User = get_user_model()
class AnotherClass(models.Model):
....
username = User.USERNAME_FIELD
Upvotes: 0
Reputation: 615
If you are already importing User model on that models.py, you can just set it to ForeignKey. be aware that it's not a string.
exch_usr = models.ForeignKey(User, on_delete=models.PROTECT)
Upvotes: 0
Reputation: 599610
If the linked model is in another app, you need to refer to that in the destination string.
exch_usr = models.ForeignKey('auth.User', on_delete=models.PROTECT)
Note, you do not need to import User at all.
Upvotes: 1