ValueError: Cannot assign "'1'": "User.campus "must be a "Campus" instance. Django Super User registration error

I am developing an application where the user needs to be on a campus. However, when creating the' superuser ' in the terminal an instance error occurs.

Note: the database is correctly pre-populated to fetch the 'campus_id'.

Django 2.0.4 and python3. 6

Error

Contas/models.py

class UserManager(BaseUserManager):

def _create_user(self, email, matricula, password, is_staff, is_superuser, **extra_fields):
    now = timezone.now()
    if not matricula:
        raise ValueError(_('The given matricula must be set'))
    email = self.normalize_email(email)
    user = self.model(matricula=matricula, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_user(self, matricula, email=None, password=None, **extra_fields):
    return self._create_user(matricula, email, password, False, False, **extra_fields)

def create_superuser(self, matricula, email, password, **extra_fields):
    user=self._create_user(matricula, email, password, True, True, **extra_fields)
    user.is_active=True
    user.save(using=self._db)
    return user

class User(AbstractBaseUser, PermissionsMixin):

username = models.CharField(_('username'), max_length=15, unique=True,
    help_text=_('Required. 15 characters or fewer. Letters, numbers and @/./+/-/_ characters'),
    validators=[ validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'),
     _('invalid'))], blank=True, null=True)
name = models.CharField(_('Nome'), max_length=100, null=True, blank=True)
email = models.EmailField(_('email address'), max_length=100, unique=True)
is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
is_trusty = models.BooleanField(_('trusty'), default=False, help_text=_('Designates whether this user has confirmed his account.'))
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
matricula = models.CharField(
    'Matricula', max_length=25, unique=True)
tipo = models.IntegerField(choices = ((1, 'Docente'),
                                (2, 'Discente'),
                                (3, 'Técnico Administrativo')), default=1)
campus = models.ForeignKey(Campus, on_delete=models.PROTECT)
cpf = models.CharField(max_length=30, unique=True, null=True, blank=True)

USERNAME_FIELD = 'matricula'
REQUIRED_FIELDS = ['name', 'email', 'tipo', 'cpf', 'campus']

objects = UserManager()

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_full_name(self):
    full_name = '%s %s' % (self.name, self.name)
    return full_name.strip()
def get_short_name(self):
    return self.name
def email_user(self, subject, message, from_email=None):
    send_mail(subject, message, from_email, [self.email])

Settings.py

AUTH_USER_MODEL = 'contas.User'

Instituicoes/models.py

class Instituicao(models.Model):
nome = models.CharField(max_length=70, null=False, blank=False)
razao_social = models.CharField(max_length=100, null=False, blank=False)
cnpj = models.CharField(max_length=30, null=False, blank=False)
sigla = models.CharField(max_length=10, null=False, blank=False)
estado = models.ForeignKey(Estado, on_delete=models.PROTECT, blank=True)

def __str__(self):
    return self.sigla

class Meta:
    verbose_name = 'Instituição'
    verbose_name_plural = 'Instituições'


class Campus(models.Model):
nome = models.CharField(max_length=50, null=False)
sigla = models.CharField(max_length=10, null=False)
endereco = models.ForeignKey(Endereco, on_delete=models.PROTECT)
instituicao = models.ForeignKey(Instituicao, on_delete=models.PROTECT)
ddd_telefone = models.CharField(max_length=2, null=False)
telefone = models.CharField(max_length=9, null=False)

def __str__(self):
    return self.nome

class Meta:
    verbose_name = 'Campus'
    verbose_name_plural = 'Campi'
Author: Pedro Grachet, 2019-01-05

1 answers

From the displayed image is trying to save the fields id. But django needs the campus instance (which has the pk). Hence the exception of type ValueError The correct would be something like:

campus = Campus.objects.get(pk=1)
 0
Author: Antonio Cleverson dos santos, 2019-05-25 05:24:09