Skip to content


Switch branches/tags

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

File and Image upload with oTree


This demonstrates how you can handle file uploads and specifically image file uploads by participants in oTree experiments. It uses standard django fields and directly attaches the files to the player object.


Here is a simple demo.


Make sure to add pillow to the requirements.txt if you want to handle image uploads.


If you are using this on Heroku, uploaded will be delated upon dyno restart. This happens every day and whenever the dynos go to "sleep". This has to do with the way dynos work. More on the issue here. Thanks to Chris on the oTree user group for pointing this out.

In its current form, my implementation is only suitable for use on your own server / computer, where you can make sure that the files are stored safely and are not deleted periodically.

Note that it is possible to store uploads in AWS S3 Storage Buckets when using Heroku, but I have not looked into this, yet. A good starting point seems to be this django app that provides a widget that handles uploads to S3 for you.


Creata a media folder in your project and add the following to your Uploaded files will be stored in the media folder.

from os import path

MEDIA_ROOT = "_media"
MEDIA_URL = "/media/"

Create in your project containing:

from otree.urls import urlpatterns
from django.conf.urls.static import static
import settings

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In your app, you need to import the model fields directly from django and specify the upload_to parameter. Files will be stored in these subdirectories of the MEDIA_ROOT setting we added earlier.

from django.db import models as django_models

class Player(BasePlayer):
    image = django_models.ImageField(upload_to="images")
    file = django_models.FileField(upload_to="files")

In, add the fields as you would do with any other fields:

class Upload(Page):
    form_model = 'player'
    form_fields = ['image', 'file']

On the template used for the file upload, it is necessary to add a property to the <form> tag that is provided by oTree. This can be accomplished by adding the following script to the bottom of the template:

{% block scripts %}
    <script type="text/javascript">
        $('#form').prop('enctype', 'multipart/form-data');
{% endblock %}

To display uploaded images or provide links to uploaded files in the templates, make sure to reference the url property of the field like this:

<img src="{{ player.image.url }}">
<a href="{{ player.file.url }}">download</a>

A serious note

Allowing people to upload files to your server is a security risk. Please make sure you know what you are doing and are ready to take the risks before using this snippet.


File uploads in oTree







No releases published


No packages published