Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the extension of a file in Django?

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

Views:

@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")   

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.

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

Thanks!

like image 938
Marcos Aguayo Avatar asked Apr 12 '13 16:04

Marcos Aguayo


People also ask

What is Django file extension?

Django Extensions is a collection of custom extensions for the Django Framework. These include management commands, additional database fields, admin extensions and much more.

How do you get a Python extension?

We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.

What is the extension of a Python file?

The Files with the . py extension contain the Python source code. The Python language has become very famous language now a days. It can be used for system scripting, web and software development and mathematics.


4 Answers

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
like image 62
dleal Avatar answered Oct 03 '22 23:10

dleal


with import mimetypes, magic:

mimetypes.MimeTypes().types_map_inv[1][
    magic.from_buffer(form.cleaned_data['file'].read(), mime=True)
][0]

gives you the extension as '.pdf' for example

https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form
http://docs.python.org/2/library/mimetypes.html#mimetypes.MimeTypes.types_map_inv
https://github.com/ahupp/python-magic#usage

like image 44
lajarre Avatar answered Oct 04 '22 01:10

lajarre


for get direct of request:

import os


extesion = os.path.splitext(str(request.FILES['file_field']))[1]

or get extesion in db - model.

import os

file = FileModel.objects.get(pk=1)  # select your object
file_path = file.db_column.path  # db_column how you save name of file.

extension = os.path.splitext(file_path)[1]
like image 22
A. Chiele Avatar answered Oct 03 '22 23:10

A. Chiele


You mean this:

u_file = request.FILES['file']            
extension = u_file.split(".")[1].lower()

if(handle_uploaded_song(file)):
    path = '%s' % u_file
    ruta =  "http://example.com/static/canciones/%s" % path
    usuario = Usuario.objects.get(pk=request.session['persona'])
    song = Cancion(autor=usuario, cancion=ruta)
    song.save()
    return HttpResponse(content_type)
like image 30
catherine Avatar answered Oct 04 '22 01:10

catherine