简体   繁体   English

在 django 中,用户应该只能看到他们上传的文件

[英]In django users should be able to see only the files which they uploaded

I'm working on a simple django website that provides its users with the ability to upload files.我正在开发一个简单的 django 网站,该网站为其用户提供上传文件的功能。 Right now all the uploaded files can be seen by every authenticated user.现在,每个经过身份验证的用户都可以看到所有上传的文件。 How can I make it so that the users can only see the files which they uploaded only?我怎样才能让用户只能看到他们上传的文件? My models:我的模特:

from django.db import models
from django.contrib.auth.models import User

class Document

title = models.CharField(max_length=100)
file = models.FileField(upload_to = 'media')

def __str__(self):
    return self.title

I believe I need to add a ForeignKey model to my Document class to trace back the user id... Unfortunately, I didn't find a way to make it work.我相信我需要在我的文档 class 中添加一个 ForeignKey model 来追溯用户 ID...不幸的是,我没有找到让它工作的方法。 Any help appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

In your Model Document add a field created_by with foreign key to user.在您的 Model 文档中,向用户添加一个带有外键的字段 created_by。 Now in your view, return only the files created by the current user.现在在您的视图中,只返回当前用户创建的文件。

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

Then in your view那么在你看来

return Document.objects.filter(created_by=user)

it will return only documents created by the user它将只返回用户创建的文档

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

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