使用generate_files_directory方法将FielField upload_更改为param do n

2024-04-19 02:07:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个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')

my 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/目录:

enter image description here

所有这些:


Tags: formurlimgreturnmodelsrequestfilesdirectory
1条回答
网友
1楼 · 发布于 2024-04-19 02:07:27

您的generate_files_directory方法错误,应该是:

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

如Django文档中所述,here方法将有两个参数:

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.

相关问题 更多 >