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).

ablerman
  • 1,523
  • 1
  • 12
  • 20

3 Answers3

3

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!

Jeremy Sharpe
  • 345
  • 1
  • 3
  • 12
1

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
  • 97,747
  • 36
  • 197
  • 212
  • the ticket isn't related to the question - the ticket is to upload a file into a blob inside the DB, while the question is to change a file field to point to an existing file on the filesystem instead of uploading... – Roee Shenberg Mar 02 '12 at 22:39
1

Set Django's FileField to an existing file is a newer duplicate, but the answer there seems better than directly modifying the database.

Community
  • 1
  • 1
Roee Shenberg
  • 1,457
  • 1
  • 13
  • 22