Reputation: 1905
Im working through Alex Pale's minimal django file upload example for django 1.8 -
I know how to get the file extension in the form, but how can I get this in the view. I'm aware I can access the file thru -
docfile=request.FILES['docfile']
View -
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
docfile=request.FILES['docfile']
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
Form -
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file'
)
Upvotes: 1
Views: 2854
Reputation: 4483
If you are asking for the extension try this:
>>> f = "this.that.ext"
>>> e = f.split(".")[-1]
>>> f
'this.that.ext'
>>> e
'ext'
>>>
You know how to get the complete filename. What you want is the last string after the "."
Upvotes: 3