如何在Django中获取文件扩展名? [英] How to get the extension of a file in Django?

查看:500
本文介绍了如何在Django中获取文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中构建一个Web应用程序。
我有一个将文件发送到views.py的表单。

I'm building a web app in Django. I have a form that sends a file to views.py.

视图:

@login_required(login_url=login_url)
def addCancion(request):
    if request.method == 'POST':
        form2 = UploadSong(request.POST, request.FILES)
        if form2.is_valid():
            if(handle_uploaded_song(request.FILES['file'])):
                path = '%s' % (request.FILES['file'])
                ruta =  "http://domain.com/static/canciones/%s" % path
                usuario = Usuario.objects.get(pk=request.session['persona'])
                song = Cancion(autor=usuario, cancion=ruta)
                song.save()
                return HttpResponse(ruta)
            else:
                return HttpResponse("-3")
        else:
            return HttpResponse("-2")
    else:
        return HttpResponse("-1")   

我正在尝试仅上传MP3文件,但是我不知道如何制作此过滤器。
我尝试了一个名为 ContentTypeRestrictedFileField(FileField):的类,但无法正常工作。

I'm trying to upload only the MP3 files, but I don't know how to make this filter. I tried a class named "ContentTypeRestrictedFileField(FileField):" and doesn't work.

如何在views.py中获取文件类型?

How can I get the file type in views.py?

谢谢!

推荐答案

您还可以使用clean()方法从窗体,用于验证它。因此,您可以拒绝不是mp3的文件。像这样的东西:

You could also use the clean() method from the form, which is used to validate it. Thus, you can reject files that are not mp3. Something like this:

class UploadSong(forms.Form):
    [...]

    def clean(self):
        cleaned_data = super(UploadSong, self).clean()
        file = cleaned_data.get('file')

        if file:
            filename = file.name
            print filename
            if filename.endswith('.mp3'):
                print 'File is a mp3'
            else:
                print 'File is NOT a mp3'
                raise forms.ValidationError("File is not a mp3. Please upload only mp3 files")

        return file

这篇关于如何在Django中获取文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆