I successfully uploaded the image using the following code:
views.py
from django.conf.urls.defaults import * from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django import template from django.template import RequestContext from mysite.uploadr.forms import UploadFileForm def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.handle_uploaded_file(request.FILES['file']) return HttpResponse(template.Template(''' <html><head><title>Uploaded</title></head> <body> <h1>Uploaded</h1> </body></html> ''' ).render( template.Context({})) ) else: form = UploadFileForm() return render_to_response('upload.html', {'form': form}, context_instance=RequestContext(request))
forms.py
from django import forms from settings import MEDIA_ROOT class UploadFileForm(forms.Form): title = forms.CharField(max_length = 50) file = forms.FileField() def handle_uploaded_file(self,file):
I would like to take one more step and associate the image with the user who is loading. I saw a few examples and fell in love with the technique in this post: https://stackoverflow.com/a/318969/
I noticed that their code uses save () and cleaned_data. Isnโt it necessary to iterate over the pieces and write to the destination folder, as in the examples in the documentation? Do i need to use cleaned_data? Just trying to figure out the most efficient ways to upload files, I saw so many different ways to do this. Your help is greatly appreciated.
source share