Thursday, November 21, 2013

Detect if uploaded file is saved to the temporary folder using Django

When uploading a file to the Django server, using HTML form and POST method, it is not always clear what is the used upload handler and if the file is saved to the temporary folder or just kept in the memory.

Here is one way to detect if the file is stored to the temporary folder or not.

def upload(request):
    uploaded_file = request.FILES['file']

    if isinstance(uploaded_file, TemporaryUploadedFile):
        # file has exceeded the value FILE_UPLOAD_MAX_MEMORY_SIZE

        # and it has been saved to the temporary folder
        print uploaded_tile.temporary_file_path()
        # closing the file will delete the file
        return "file too large"
        # file is instance of InMemoryUploadedFile
    # handle file
    return "ok"

Other comparison function that can be used is:

    if hasattr(uploaded_file, 'temporary_file_path'):


Wednesday, November 20, 2013

How to start using South database migration tool in your Django project

If you are working with Django application using database, at some point you may need change your database schema. In my projects, when working with extreme style, the database changes are frequent.

The 'syncdb' handles new tables, but it does not update changes to the existing tables. One solution is to start using migration tool 'South'.

A lot of documentation for the South exists, but for some reason I was not able to get it up and running as easily as I thought I would. So I wrote the steps you have to take when starting to use South. I hope it helps.

How to start using South in your Django project

1. start using south by setting it to
    - add 'south' to INSTALLED_APPS in your
2. create needed databases, if you are starting from the scratch
    - python syncdb
3. create initial migration files
    - python schemamigration APPNAME --initial
4. make the first migration, use parameter --fake to avoid "table already exists error"
    - python migrate APPNAME --fake
5. create migration file for fixtures (if you have any)
    - datamigration APPNAME load_fixtures
6. edit the fixture file "", search the file from "migrations" folder
    - edit the function forwards() to include json fixture of your own
        def forwards(self, orm):
       from import call_command
       call_command("loaddata", "my_initial_data.json")

7. run the migration to import the fixtures
    - python migrate APPNAME