views:

118

answers:

2

The user uploads a file and I convert that file to a new format. How do I insert the created file into the DB?

When I do the obvious field.file = newfile, it tries to upload it. So, I guess the question is, how do I add a file to the database without having it try and write the file to the filesystem?

--Edit-- I don't want to store the file in the DB. I just want to set the path that the FileField points to without having the FileField try to write the file to disk (because it's already on disk).

+1  A: 

Short answer, there is no direct way to do this in Django, and the core devs aren't keen on it - see ticket #652.

Dominic Rodger
+1  A: 

You can of course still do this (as I just have) by directly modifying the database. You can create the sql code to execute using a django-based script, and then run it through your database (in my case sqlite3):

# Set up django environment
from django.core.management import setup_environ
from app import settings
setup_environ(settings)

from project.app.models import MyModel

# Prints sql to update file locations since django won't :(

for myModel in MyModel.objects.all():
  # You can do the below even better if you use the same method as the model uses
  # to generate upload_to
  file_name = 'my_file_this_should_depend_on_myModel'
  file_location = 'path/to/file/dir/%s' % file_name
  print "UPDATE app_mymodel SET file_field='%s' WHERE id=%s;" % \
    (file_location, myModel.id)

Then use the output of this script and run it through your DB!

Smug Duckling