django get_available_name()得到一个意外的关键字参数'max_length'

时间:2017-06-06 11:42:30

标签: python django filefield

我想用my django Model覆盖文件。因此,如果我上传'one'并稍后上传'two','two'应该覆盖'one'(在文件系统上)。但是我得到了一个错误。

这是我的模特:

class StudentAssignment(models.Model):
    file0 = models.FileField(upload_to=use_solution_path, storage=OverwriteStorage(), validators=[validate_file_extension])

这是存储。

import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage


class OverwriteStorage(FileSystemStorage):
    def get_available_name(self, name):
        """
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        """
        # If the filename already exists, remove it as if it was a true file system
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

错误:

  [...]
  File "/home/mb/.local/lib/python3.5/site-packages/django/db/models/fields/files.py", line 95, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
  File "/home/mb/.local/lib/python3.5/site-packages/django/core/files/storage.py", line 53, in save
name = self.get_available_name(name, max_length=max_length)
TypeError: get_available_name() got an unexpected keyword argument 'max_length'

我是django的新手,不知道该怎么做。有人可以帮忙吗?谢谢:))

2 个答案:

答案 0 :(得分:5)

documentation for file storage classes清楚地表明get_available_name采用max_length关键字参数。所以你需要至少接受这个论点,即使你不使用它。

def get_available_name(self, name, max_length=None):

答案 1 :(得分:0)

更改

def get_available_name(self, name):

def get_available_name(self, name, max_length=None):