Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django File Uploads and Model FileField

I'm sooo close... but I don't quite see the connection from the upload view to the model. When I use the callback in the model's FileField the upload works, but I'm not sure where the actual file copy is taking place. The goal is to make sure that chunking is happening, but the file copy action seems to be hidden somewhere?

Here's what I have:

Model:

def get_media_upload_dir(instance, filename):
    user_id  = instance.user.id
    upload_dir = "%s/%d/%s" % (settings.MEDIA_ROOT, user_id, filename)
    print "Upload dir set to: %s" % upload_dir
    return upload_dir

class MediaFile(models.Model):
    media_file     = models.FileField(upload_to=get_media_upload_dir)
    download_count = models.PositiveIntegerField(default=0)

View:

def file_upload(request, course_id):    
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded = form.cleaned_data['file_upload']
            mediaFile = MediaFile(media_file=uploaded,
                                owner=request.user.profile,
                                creator=request.user.profile)
            mediaFile.save()

            return HttpResponseRedirect('/course/%s/' % course_id)
    else:
        form = FileUploadForm()
    return render_to_response('course/file_upload.html', {'form':form,'course':course}, context_instance=RequestContext(request))
like image 402
Scott Avatar asked Jul 05 '10 18:07

Scott


1 Answers

The storing happens here: http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py#L90. Django uses it's own API for accessing the file storage: http://docs.djangoproject.com/en/dev/ref/files/storage/. But if chunking is what you need you can go with Bartek's proposal!

like image 140
Bernhard Vallant Avatar answered Oct 04 '22 23:10

Bernhard Vallant