代码之家  ›  专栏  ›  技术社区  ›  gruszczy

Django:保存临时文件的模型

  •  1
  • gruszczy  · 技术社区  · 15 年前

    在某些情况下,用户可以向我的服务器发送临时文件。我想跟踪这些临时文件(因为它们稍后会被使用,我想知道,什么时候可以删除它们——或者当它们不被使用并且可以收集时)。我应该用什么型号的?我会用 AJAX (和) iframe )

    编辑

    如果我在模型中使用 FileField ,如何处理文件上载?你能给我举个例子吗,我的函数应该如何放置文件 request.FILES 到A FielField .

    1 回复  |  直到 13 年前
        1
  •  3
  •   Steve Jalim    13 年前

    存储文件的方式与文件是否通过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()方法,则需要一些代码来创建临时文件包装器对象, 某物 这样,根据您的需要:

    ....
    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/')