I'm working on a simple django website that provides its users with the ability to upload files. 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. Any help appreciated. Thank you.
In your Model Document add a field created_by with foreign key to user. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.