How can I use django.core.files.File
The docs for django.core.files.File imply I can do this: print File(open(path)).url
but the File object has no attribute 'url' However, django.db.models.fields.files.FieldFile extends File 开发者_StackOverflowand does have all the attributes described in the docs for File, but I can't create one without giving it a model field.
Cheers, Jake
Regardless of what the Django doc says, if you look at the code for the File class, I don't see it there. Following Ignacio's suggestion, you can derive from the Django File
and use the MEDIA_ROOT and MEDIA_URL settings to implement the property you're looking for...
from django.core.files import File
from django.conf import settings
class UrlFile(File):
def _get_url(self):
root_name = self.name.replace(settings.MEDIA_ROOT, '')
return '%s%s' % (settings.MEDIA_URL, root_name)
url = property(_get_url)
If you derive from file
then you can give it any attributes you like:
class MyFile(file):
def foobar(self):
print 'foobar'
f = MyFile('t.txt', 'r')
f.foobar()
Thanks Guys. I've solved my problem by writing a custom class, it's not as powerful as the Django one would be if I could use it, but it works for my current application. I'll open a ticket about the docs.
精彩评论