2

I am a newbie in django and I have a question about how I can save and show only the data of logged user - since my application is multi-tenant.

my view

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

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

class ProjetoList(ListView):
    paginate_by = 2
    model = Projeto

my model

class Projeto(models.Model):
    nomeProjeto = models.CharField(max_length=20)
    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)

Thank you very much!

gPxl
  • 95
  • 14

2 Answers2

1

Add

user = models.ForeignKey(User, on_delete=models.CASCADE)

to Projecto model. Then, in your view, set project.user = self.request.user before saving your project model.

Alex Vyushkov
  • 650
  • 1
  • 6
  • 21
  • Ok, I added the line but I got the message "IntegrityError at /projeto/cadastrarProjeto/ NOT NULL constraint failed: projeto_projeto.user_id" . In my view I wrote def get_queryset(self): logged_user = self.request.user Projeto.user = self.request.user return Projeto.objects.filter(User=logged_user) – gPxl Oct 20 '20 at 01:56
  • I believe that you can refer to object created by CreateView as `self.object`, so it is probably should be `self.object.user = self.request.user` – Alex Vyushkov Oct 20 '20 at 02:06
0

I think you are doing it completely wrong.

You shouldn't be using get_queryset() at all in CreateView - https://stackoverflow.com/a/24043478/4626254

Here's is what you can try instead.

  1. Add a user field in Project model and apply migrations. user = models.ForeignKey(User, on_delete=models.CASCADE)
  2. Create a class inheriting Generic APIView instead of CreateView.
  3. Create a POST method like def post(self, request): inside that class and get all the details for creating a Projeto object in the request payload using request.data or request.POST.
  4. Get the logged in user using request.user
  5. Create a Projecto object with all this information as Projeto.objects.create(**your_other_fields, user=request.user)
  6. Next time when filtering the objects, use a filter on user field like user=request.user.
Underoos
  • 4,708
  • 8
  • 42
  • 85