Django Added ForeignKey object in Custom User Model, when creating users im getting value error

61 Views Asked by At

Django Added ForeignKey object in Custom User Model, when creating users im getting value error this is user model(AppUser) having foreignkey in it, the error is as folllowed, ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. tried with just instance also user = User.objects.create_user(email='[email protected]',branch=Branches.objects.get(name="Temp_Branch"))

class AppUser(AbstractUser):
    username = None
    secId = models.CharField(max_length=255,default=sec.token_urlsafe(16))
    email = models.EmailField(unique = True, null=False)
    password = models.CharField(max_length=255)
    branch = models.ForeignKey(Branches,on_delete=models.SET(tempBranch),null=False)
    is_verified = models.BooleanField(default = False)
    USERNAME_FIELD = "email"
`    REQUIRED_FIELDS = ['branch']
    objects = UserManager()
class UserManager(BaseUserManager):
    def create_user(self, email, branch, password = None,**extra_fields):
        if not email:
            raise ValueError("Email is required")
        if not branch:
            raise ValueError("Need Branch")
        email = self.normalize_email(email.lower())
        user = self.model(email = email, branch=    branch, **extra_fields)
        user.set_password(password)
        user.save(using = self.db)
        return user
    def create_superuser(self, email,branch, password = None, **extra_fields):
        extra_fields.setdefault("is_staff",True)
        extra_fields.setdefault("is_superuser",True)
        extra_fields.setdefault("is_active",True)
        return self.create_user(email,branch,password, **extra_fields)
>>> user = User.objects.create_user(email='[email protected]',branch=Branches.objects.get(name="Temp_Branch").id)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/Varun/Spaces/spaces/core/manager.py", line 9, in create_user
    email = self.normalize_email(email.lower())
  File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/base.py", line 543, in __init__
    _setattr(self, field.name, rel_obj)
  File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 283, in __set__
    raise ValueError(
ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance.
1

There are 1 best solutions below

3
On

In this relation, I guess you need to pass the instance itself (the Branch object), not the id.

user = User.objects.create_user(email='[email protected]',branch=Branches.objects.get(name="Temp_Branch"))

simply delete the ".id" it should work.