简体   繁体   English

在Django管理中获取上传文件的URL

[英]Getting the url of an uploaded file in django admin

I have an application in which I am uploading a file using Django's admin site. 我有一个应用程序,在其中使用Django的管理站点上传文件。 I need to return the url of the file so that it can be used by another function. 我需要返回文件的url,以便其他功能可以使用它。 The process works just fine apart from the fact that I am able to get the name of the original file and not the file that is saved by the application. 除了能够获得原始文件的名称而不是应用程序保存的文件之外,该过程还可以正常工作。 For instance if the file to be uploaded is named somefile.xxx and django saves it as somefile_1.xxx because that somefile.xxx already exists on the server I am not able to return somefile_1.xxx but I am geting the original file name. 例如,如果要上载的文件名为somefile.xxx,并且django将其另存为somefile_1.xxx,因为服务器上已经存在somefile.xxx,则无法返回somefile_1.xxx,但是我得到的是原始文件名。 this is my code at the moment. 这是我目前的代码。

admin.py 管理员

def add_view(self, request, form_url="", extra_context=None):
        ...

        ModelForm = self.get_form(request)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES)
            if form.is_valid():
                url = MEDIA_URL+'files/'+request.FILES['filename'].name
                url = iri_to_uri(url)
                title = form.cleaned_data['title']
                name = request.FILES['filename'].name
                newname = os.path.splitext(request.FILES['filename'].name)[0]
                data = utils.convert(url, title, newname)
                print data

        return super(FileAdmin, self).add_view(request, form_url="", extra_context=extra_context)

Solution: 解:

def save_model(self, request, obj, form, change):

        ...

        obj.save()

        url = obj.video.url

        title = obj.title

        newname = str(obj.id)

        data = utils.convert(url, title, newname)
        print data

The add_view is pre save - so the files should be in memory and thus no filenames should be set yet. add_view是预先保存的-因此文件应位于内存中,因此尚无文件名设置。

You'd need to override ModelAdmin.save_model and access the file after calling obj.save() to account for the possibility that django renamed your file. 您需要在调用obj.save()之后重写ModelAdmin.save_model并访问文件,以解决django重命名文件的可能性。

FileField has an url function to retrieve exactly what you want i guess https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage FileField具有url函数,可准确检索您想要的内容https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage

See the point 3 under the storage section 请参阅“存储”部分下的第3点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM