Attributeerror - 'User' Object has no attribute 'project' - Django

Asked

Viewed 518 times

2

I am new in Django and have a question. I made a system that saves the contents of the respective logged in user. Thus, each user will have their own content when viewing (multi-tenant system).

However, I have the following error message

AttributeError at /projeto/visualizarProjeto/
'User' object has no attribute 'projeto'
Request Method: GET
Request URL:    http://127.0.0.1:8000/projeto/visualizarProjeto/
Django Version: 3.1.2
Exception Type: AttributeError
Exception Value:    
'User' object has no attribute 'projeto'

Follows my model

class Projeto(models.Model):
    nomeProjeto = models.CharField(max_length=20)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    descricao = HTMLField()
    dtInicio = models.DateField(auto_now=False, auto_now_add=False)
    deadline = models.DateField(auto_now=False, auto_now_add=False)
    nomeSprint = models.CharField(max_length=30)
    status = models.CharField(max_length=20)

My view

class ProjetoCreate(CreateView):
    model = Projeto
    fields = ['nomeProjeto',
              'descricao',
              'dtInicio',
              'deadline',
              'nomeSprint',
              'status',
             ]

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.save()
        return super(ProjetoCreate, self).form_valid(form)



@method_decorator(login_required, name='dispatch')
class ProjetoList(ListView):
    paginate_by = 10
    model = Projeto

    def get_queryset(self):
        usuarioLogado = self.request.user.projeto.user
        return Projeto.objects.filter(User=usuarioLogado)

As the respective logged-in user can see only its registered content, without giving this error?

Thank you very much.

  • 1

    How did you not set the parameter related_name in the attribute user of model Projeto, I believe you need to do the backreference by attribute projeto_set ("<class>_set"), which is used by default.

1 answer

1


def get_queryset(self):
        usuarioLogado = self.request.user
        return Projeto.objects.filter(user=usuarioLogado)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.