[英]How do I assign specific users to a user-uploaded file so they can modify it/delete it (Django + Apache)
我在Linux中使用django 1.10 + Apache。 我已經創建了一個小型的Webapp來上傳文檔(使用dropzone.js),並希望實現用戶指定誰可以查看/修改/刪除特定文件的功能,但是我不知道該怎么做。 我嘗試使用ManyToManyField,但可能即時通訊沒有正確理解Field本身。
“文檔”模型是這樣的:
class Document(models.Model):
file = models.FileField(upload_to = 'files/')
#validators=[validate_file_type])
uploaded_at = models.DateTimeField(auto_now_add = True)
extension = models.CharField(max_length = 30, blank = True)
thumbnail = models.ImageField(blank = True, null = True)
is_public = models.BooleanField(default = False)
accesible_by = models.ManyToManyField(User) #This is my attempt at doing this task.
def clean(self):
self.extension = self.file.name.split('/')[-1].split('.')[-1]
if self.extension == 'xlsx' or self.extension == 'xls':
self.thumbnail = 'xlsx.png'
elif self.extension == 'pptx' or self.extension == 'ppt':
self.thumbnail = 'pptx.png'
elif self.extension == 'docx' or self.extension == 'doc':
self.thumbnail = 'docx.png'
def delete(self, *args, **kwargs):
#delete file from /media/files
self.file.delete(save = False)
#call parent delete method.
super().delete(*args, **kwargs)
#Redirect to file list page.
def get_absolute_url(self):
return reverse('dashby-files:files')
def __str__(self):
return self.file.name.split('/')[-1]
class Meta():
ordering = ['-uploaded_at']
我的視圖來處理文檔的創建:
class DocumentCreate(CreateView):
model = Document
fields = ['file', 'is_public']
def form_valid(self, form):
self.object = form.save(commit = False)
## I guess here i would Add the (self.request.user) to the accesible_by Field.
self.object.save()
data = {'status': 'success'}
response = JSONResponse(data, mimetype =
response_mimetype(self.request))
return response
在此先感謝任何人的任何想法或建議...
您有一個模型和一個希望可以用於添加新文檔的視圖,但是您仍然需要執行許多步驟。 您需要一個位置來分配可以查看/修改/刪除文件的用戶。 如果您需要存儲訪問級別(查看/刪除...),那么accessible_by將不足以滿足您的需求,並且可以通過一個貫通表來添加更多信息,例如訪問級別。
您需要為用戶將請求的各種操作(例如視圖,刪除...)編寫視圖,並在此處確保用戶具有正確的特權。 一種實現是獲取request.user和文檔ID,查找用戶是否有權執行其操作,返回http未經授權的異常或允許執行操作。
編輯:我的問題是關於如何分配用戶權限到每個單獨的文件
如果我們將其保留為從django級別訪問控制,請使用已有的文檔模型,並已采取一些步驟,對於每個文檔,您都可以分配用戶(accessible_by)。 這樣的事情可以幫助您入門:
from django.core.exceptions import PermissionDenied
def view_document(request, doc_pk):
doc = get_object_or_404(Document, pk=doc_pk)
if not doc.accessible_by.filter(username=request.user.username):
raise PermissionDenied
#perform rest of action
還是您要使用權限框架本身?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.