使用 generate_files_directory 方法更改 FielField upload_to 参数不起作用

Use the generate_files_directory method to change the FielField upload_to param do not work

我写了一个generate_files_directory方法来生成上传路径:

def generate_files_directory(self,filepath):
    url = "images/%s" % (filepath)
    return url

型号如下:

class Upload(models.Model):
    filepath = models.CharField(max_length=64, default="imgs/test/")
    pic = models.FileField(upload_to=generate_files_directory)
    upload_date=models.DateTimeField(auto_now_add =True)

表单代码如下:

class UploadForm(ModelForm):
    class Meta:
        model = Upload
        fields = ('pic', 'filepath')

我的views.py:

def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)
        if img.is_valid():
            img.save()
            return HttpResponseRedirect(reverse('imageupload'))
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'home.html',{'form':img,'images':images})

然后我写了一个home.html来上传文件:

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>picture</h1>
    <form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %} {{form}}
        <input type="submit" value="Upload" />
    </form>
    {% for img in images %}
        {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
        ({{img.upload_date}})<hr />
    {% endfor %}
</div>

但是好像没有上传到生成路径,还是上传到/images/目录:

都在里面:

你的generate_files_directory方法有误,应该是:

def generate_files_directory(instance, filename):
    url = "images/%s" % instance.filepath # will output something like `images/imgs/test/`
    return url

如 Django 文档中所述hereupload_to 方法将被赋予两个参数:

instance
An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached.

In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.

filename The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.