无法指定“'Mary'”:“Aluno.mother_name”必须是“Aluno”实例。当我尝试访问子类“Aluno”

时间:2015-06-11 22:45:00

标签: python django django-authentication

我正在开发一个具有多个用户的系统,我正在继承Django User。 我有两个用户:“aluno”和“教授”。 还有一个基类UserAlunoProfessor继承自User。 的 models.py

帐户/ models.py

class User(AbstractBaseUser, PermissionMixin):
    username = models.CharField('Usuário', max_length=30, unique=True,
        validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'),
            'O nome de usuário só pode conter letras, digitos ou os '
            'seguintes caracteres: @/./+/-/_', 'invalid')]
    )

    nome = models.CharField('Nome', max_length=100)
    email = models.EmailField('E-mail', unique=True) # blank=True?
    instituicao = models.CharField('Instituição', max_length=200)
    SEXO_CHOICE = ((0, 'Masculino'), (1, 'Feminino'))
    sexo = models.IntegerField('Sexo', choices=SEXO_CHOICE, default=0)
    imagem_perfil = models.ImageField('Imagem do perfil', upload_to='media/img/%Y/%m/%d', blank=True)
    is_active = models.BooleanField('Está ativo?', blank=True, default=True)
    is_staff = models.BooleanField('É administrador?', blank=True, default=False)
    date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.nome

    def get_short_name(self):
        return str(self)

    def get_full_name(self):
        return self.nome

    class Meta:
        verbose_name = 'Usuário'
        verbose_name_plural = 'Usuários'

aluno / models.py

class Aluno(User):
    mother_name = models.CharField('Mother name ', max_length=100)

    class Meta:
        verbose_name = 'Aluno'
        verbose_name_plural = 'Alunos'

教授/ models.py

class Professor(User):
    endereco = models.CharField('Endereço', max_lenght=100)

    class Meta:
        verbose_name = 'Professor'
        verbose_name_plural = 'Professores'

views.py

def dashboard_aluno(request):
    user = User.objects.all()
    aluno = Aluno.objects.all()
    professor = Professor.objects.all()
    print(user)
    print(aluno)# o erro acontece nessa linha
    print(professor)
    turma_aluno = Turma.objects.filter(alunos__id__contains=request.user.id)
    disciplina_aluno = Disciplina.objects.filter(turmas__id__contains=turma_aluno[0].id)
    template_name = 'dashboard_aluno.html'
    context = {'turma_aluno': turma_aluno, 'disciplina_aluno': disciplina_aluno}
    return render(request, template_name, context)

Login正在与两个用户合作,但是当我尝试访问子类字段时,我收到了这个错误:

File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/rede_social/conta/views.py" in dashboard_aluno
  18.     print(aluno)
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/query.py" in __repr__
  116.         data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/query.py" in __iter__
  141.         self._fetch_all()
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/query.py" in _fetch_all
  966.             self._result_cache = list(self.iterator())
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/query.py" in iterator
  275.                     obj = model(*row_data)
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/base.py" in __init__
  382.                 setattr(self, field.attname, val)
File "/home/andre/andre/ifce/iniciacaocientifica/rede_social/projeto/venv/lib/python3.4/site-packages/django/db/models/fields/related.py" in __set__
  454.                     self.related.opts.object_name,

Exception Type: ValueError at /conta/dashboard_aluno/
Exception Value: Cannot assign "'Mary'": "Aluno.mother_name" must be a "Aluno" instance.

我是Django的新手,所以任何建议或提示都将受到赞赏。 Django 1.7.7和python 3.4

Ps。:这是多个用户的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

经过一周的研究,我发现自己做错了什么。 我把子类:ProfessorAluno放在同一个应用程序中,然后工作!很简单。 我不知道为什么,但是工作。

帐户/ models.py

class User(AbstractBaseUser, PermissionMixin):
    username = models.CharField('Usuário', max_length=30, unique=True,
        validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'),
            'O nome de usuário só pode conter letras, digitos ou os '
            'seguintes caracteres: @/./+/-/_', 'invalid')]
    )

    nome = models.CharField('Nome', max_length=100)
    email = models.EmailField('E-mail', unique=True) # blank=True?
    instituicao = models.CharField('Instituição', max_length=200)
    SEXO_CHOICE = ((0, 'Masculino'), (1, 'Feminino'))
    sexo = models.IntegerField('Sexo', choices=SEXO_CHOICE, default=0)
    imagem_perfil = models.ImageField('Imagem do perfil', upload_to='media/img/%Y/%m/%d', blank=True)
    is_active = models.BooleanField('Está ativo?', blank=True, default=True)
    is_staff = models.BooleanField('É administrador?', blank=True, default=False)
    date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.nome

    def get_short_name(self):
        return str(self)

    def get_full_name(self):
        return self.nome

    class Meta:
        verbose_name = 'Usuário'
        verbose_name_plural = 'Usuários'

class Aluno(User):
    mother_name = models.CharField('Mother name ', max_length=100)

    class Meta:
        verbose_name = 'Aluno'
        verbose_name_plural = 'Alunos'

class Professor(User):
    endereco = models.CharField('Endereço', max_lenght=100)

    class Meta:
        verbose_name = 'Professor'
        verbose_name_plural = 'Professores'