I want my User objects in Django to be linked to a Client object (which I create). To do so I extend the User model with a one-to-one link with a Profile class (which I create) class Profile that links User & Client. I followed the instructions from https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html So far so good.
However when I create a User object I dont have access by default to I want my User objects
My models.py:
from django.contrib.auth.models import User
[...]
class Client(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
[...]
class Profile(models.Model):
need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES')
user = models.OneToOneField(User, on_delete=models.CASCADE)
client = models.ForeignKey(Client, on_delete=models.DO_NOTHING)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
The problem comes when I make my migrations / runserver (my app is called 'dashboard'):
django.db.utils.ProgrammingError: relation "dashboard_client" does not exist LINE 1: ...nque_id", "dashboard_client"."date_creation" FROM "dashboard...
because of the need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES') (no problems if I comment it out).
I can work around the problem by manually creating a client in the db called 'NEED TO ADD CLIENT IN ADMIN > PROFILES' and then run my migrations and deploy but I'm looking for a better way of doing this, especially when I deploy from scratch in prod.
I tried to override the def ready(self) function in apps.py, which is a function that runs when the apps boots. Unfortunately it needs to have the correct models.py before running.
Your thoughts and ideas are appreciated!
getan instance of aClientin yourProfilemodel. At the outset, you don't actually have any client instances, so your call toClient.objects.get()is rightfully returning an error. This is why this problem is fixed when you manually add a client to the DB that matches that name. I'm unsure what your goal is with theneed_setupfield, but as it is right now, it's not actually a field, it's a queryset, which should not be in a Model. If you could clear up whatneed_setupis supposed to be, we can probably figure out how to fix ituserfrom the post-save signalcreate_user_profile. In that case, you can simply setneed_setupas a BooleanField with a default value ofTrue. Then, override thesavemethod to check if the object has aclientlinked. Ifclientis still null, keepneed_setupas True, otherwise set to False.