Creating an object with a FileField programmatically

3,844 views
Skip to first unread message

Vincent Foley

unread,
Apr 14, 2009, 4:04:39 PM4/14/09
to Django users
Hello,

I want to be able to add files inside a model to test that model.
However, I'm unable to find in the documentation any mention on how to
do so. I asked on IRC and somebody suggested the following:

from django.core.files import File
from myproject.myapp.models import MyModel
fd = open('/path/to/file')
f = File(fd)
obj = MyModel.objects.create(file_field=f)
f.close()
fd.close()


However, when I try to access obj, I get the following exception:
SuspiciousOperation: Attempted access to '/path/to/file' denied.

Is it how one is supposed to "attach" file into a model? If so, what
could be causing my problem?

Thanks,

Vincent

Alex Gaynor

unread,
Apr 14, 2009, 4:11:56 PM4/14/09
to django...@googlegroups.com
If the file isn't already relative to your MEDIA_ROOT you need to do:

m = MyModel()
m.file_field.save('new_file_name', open('/path/to/file').read()).

Alex
--
"I disapprove of what you say, but I will defend to the death your right to say it." --Voltaire
"The people's good is the highest law."--Cicero

chachra

unread,
Apr 26, 2009, 8:21:44 PM4/26/09
to Django users
I am trying something similar and getting:

Cannot create a consistent method resolution
order (MRO) for bases File, FieldFile

Using Django 1.1b

Cheers!
Sumit

Malcolm Tredinnick

unread,
Apr 26, 2009, 9:14:20 PM4/26/09
to django...@googlegroups.com
On Sun, 2009-04-26 at 17:21 -0700, chachra wrote:
> I am trying something similar and getting:
>
> Cannot create a consistent method resolution
> order (MRO) for bases File, FieldFile

Then you're not doing something too similar, because that's quite
different to the error in the post you quote. It involved file fields,
but that's it.

So what are you doing to trigger this error? What's a really small
example that demonstrates the problem?

Based on the error, you may have found the same thing as ticket #10249,
in which case the solution is to wait for that to be fixed. It's on the
1.1 milestone.

Regards,
Malcolm


Reply all
Reply to author
Forward
0 new messages