简体   繁体   English

在django中保存当前登录用户的数据

[英]Save the data of current logged user in django

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.我是 django 的新手,我有一个关于如何保存显示登录用户数据的问题 - 因为我的应用程序是多租户的。

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!非常感谢!

Add添加

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

to Projecto model.到 Projecto 模型。 Then, in your view, set project.user = self.request.user before saving your project model.然后,在您的视图中,在保存您的项目模型之前设置project.user = self.request.user

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你不应该在CreateView使用get_queryset() - 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.Project模型中添加用户字段并应用迁移。 user = models.ForeignKey(User, on_delete=models.CASCADE)
  2. Create a class inheriting Generic APIView instead of CreateView .创建一个继承 Generic APIView而不是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 .创建一个 POST 方法,如def post(self, request):在该类中,并使用request.datarequest.POST在请求有效负载中创建Projeto对象的所有详细信息。
  4. Get the logged in user using request.user使用request.user获取登录用户
  5. Create a Projecto object with all this information as Projeto.objects.create(**your_other_fields, user=request.user)使用所有这些信息创建一个Projecto对象作为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 .下次过滤对象时,请在user字段上使用过滤器,例如user=request.user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM