Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How instanciate table in createsuperuser

I have two tables Employee and Sector, the employee table has for foreign key the sector code (sectorCode) property of the Sector table. The Employee table inherits from the AbstractBaseUser class.
I would like to create a superuser with the command python manage.py createsuperuser.
I get an error: ValueError: Cannot assign "'Code1'": "Employee.sectorCode" must be a "Sector" instance.
(I added in the Sector table a row NameSector1; Code1)

I input these values:

λ python manage.py createsuperuser
registrationNumber: 001
Name: TestN1
FirstName: TestFN1
sectorCode: Code1
Password: ...

Error ...

How can I instantiate sector class in dialog ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class MyUserManager(BaseUserManager):
    
    def create_user(self, registrationNumber, firstName, name, sectorCode, password=None):
        if not firstName: raise ValueError("firstName required")
        if not name: raise ValueError("name required")
        if not registrationNumber: raise ValueError("registrationNumber required")
        if not sectorCode: raise ValueError("sectorCode required")
        
        user=self.model(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode)
        user.set_password(password); user.save()
        return user
    
    def create_superuser(self, firstName, name, registrationNumber, sectorCode, password=None):
        user=self.create_user(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode, password = password)
        user.is_admin=True; user.is_superuser=True
        user.save()
        return user

class Sector(models.Model):
    nameSector = models.CharField(verbose_name = "nameSector", max_length=50)
    sectorCode = models.CharField(verbose_name = "sectorCode", max_length=3, primary_key=True)
    
    class Meta: db_table = "Sector"
    
class Employee(AbstractBaseUser):
    firstName = models.CharField(verbose_name = "firstName", max_length=20)
    name = models.CharField(verbose_name = "name", max_length=20)
    registrationNumber = models.CharField(verbose_name="registrationNumber", max_length=20, primary_key=True)
    sectorCode = models.ForeignKey(Sector, on_delete=models.CASCADE)
    
    USERNAME_FIELD="registrationNumber"
    REQUIRED_FIELDS = ["name", "firstName", "sectorCode"]
    objects = MyUserManager()
    class Meta: db_table = "Employee"

>Solution :

If you know the sector exists, you can work with:

class MyUserManager(BaseUserManager):
    def create_user(
        self, registrationNumber, firstName, name, sectorCode, password=None
    ):
        if not firstName:
            raise ValueError("firstName required")
        if not name:
            raise ValueError("name required")
        if not registrationNumber:
            raise ValueError("registrationNumber required")
        if not sectorCode:
            raise ValueError("sectorCode required")

        user = self.model(
            firstName=firstName,
            name=name,
            registrationNumber=registrationNumber,
            sectorCode_id=sectorCode,
        )
        user.set_password(password)
        user.save()
        return user

    # …

If you want to create a Sector in case that one is missing, you can use:

class MyUserManager(BaseUserManager):
    def create_user(
        self, registrationNumber, firstName, name, sectorCode, password=None
    ):
        if not firstName:
            raise ValueError("firstName required")
        if not name:
            raise ValueError("name required")
        if not registrationNumber:
            raise ValueError("registrationNumber required")
        if not sectorCode:
            raise ValueError("sectorCode required")

        sector, __ = Sector.objects.get_or_create(
            sectorCode=sectorCode, defaults={'nameSector': sectorCode}
        )

        user = self.model(
            firstName=firstName,
            name=name,
            registrationNumber=registrationNumber,
            sectorCode=sector,
        )
        user.set_password(password)
        user.save()
        return user

    # …

Code1 will however not be valid, since the sector code has a maximum length of three characters.


Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: first_name instead of firstName.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading