2010-08-16 73 views
1

在某些情況下,用戶可以發送臨時文件到我的服務器。我想跟蹤這些臨時文件(因爲它們稍後會被使用,並且我想知道,何時可以刪除它們 - 或者何時它們不被使用並且可以被收集)。我應該使用什麼樣的模型?我將使用AJAX(和iframe)發送這些文件。django:保留臨時文件的模型

編輯

如果我在模型FileField使用,我應該如何處理文件上傳?你能否展示一些示例代碼片斷,我的函數應該如何將文件request.FILES設置爲FielField

+0

常規問題出現了什麼問題http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield ? – 2010-08-16 19:37:10

+0

我加了一個小小的更新。 – gruszczy 2010-08-16 20:04:04

回答

3

如何存儲文件與是否通過AJAX進來無關。您的視圖仍然需要處理多部分表單數據,並將其存儲在數據庫和服務器文件系統中,就像在Django中上載的任何其他文件一樣。

就模型而言,這樣的事情呢?

class TemporaryFileWrapper(models.Model): 
    """ 
    Holds an arbitrary file and notes when it was last accessed 
    """ 
    uploaded_file = models.FileField(upload_to="/foo/bar/baz/") 
    uploading_user = models.ForeignKey(User) 
    uploaded = models.DateTimeField(blank=True, null=True, auto_now_add=True)   
    last_accessed = models.DateTimeField(blank=True, null=True, 
             auto_now_add=False, auto_now=False) 


    def read_file(record_read=True): 
     #...some code here to read the uploaded_file 
     if record_read: 
      self.last_accessed = datetime.datetime.now() 
      self.save() 

對於基本的文件上傳處理see the official documentation,但其中的例子有handle_uploaded_file()方法,你需要一些代碼,創建了一個TemporaryFileWrapper對象,東西這樣,根據您的需要:

.... 
form = ProviderSelfEditForm(request.POST, request.FILES) #this is where you bind files and postdata to the form from the HTTP request 
if form.is_valid(): 
    temp_file_wrapper = TemporaryFileWrapper() 
    temp_file_wrapper.uploaded_file = 
         form.cleaned_data['name_of_file_field_in_your_form'] 
    temp_file_wrapper.uploading_user = request.user #needs an authenticated user 
    temp_file_wrapper.save() 

    return HttpResponseRedirect('/success/url/') 
+0

你能否在更新的問題上給我建議? – gruszczy 2010-08-16 20:04:22

+0

是的,就是這一點 - 我沒有形式。我只是從'request.FILES'獲得'UploadedFile'。我可以以某種方式將文件從此分配給FileField對象嗎? – gruszczy 2010-08-16 21:28:05

+0

製作一個簡單的表單,將數據綁定到數據上,然後按照我所顯示的方式訪問它,或者閱讀我已鏈接的教程(具體而言,http://docs.djangoproject.com/zh/dev/topics/http/file上傳/?from = olddocs#handling-uploaded-files)來處理未綁定到表單的文件。 – 2010-08-16 21:44:31