tags:

views:

68

answers:

3

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 and does have all the attributes described in the docs for File, but I can't create one without giving it a model field.
All I want it something that does what the docs for django.core.files.File (link above) say it does, take a python file and give it attributes like 'url' and 'path' and 'name', can anyone help?

Cheers, Jake

A: 

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()
Ignacio Vazquez-Abrams
Yes, but the django docs say that django.core.files.File does that and gives it attributes like url, I realise I could write one myself to do that, but if I can use a django class it would be better.
Jake
+1  A: 

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)
T. Stone
A: 

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.

Jake