0

I would like to make a system, which is photos belong to projects. I also enabled that I can upload a zipfile directly for a project and it will unzip and register the photos to the specified project. However, I am having troubles while defining the Photo class.

I need to get the value of Project.file_zip.path with the current instance for defining img field's upload_to attribute. However, when I tried like below, it returns with AttributeError: 'ForeignKey' object has no attribute 'file_path'. How do I fix that?

class Project(models.Model):
....
owner=models.ForeignKey(User)
file_zip=models.FileField(upload_to='projects/%Y/%m/%d')

def __unicode__(self):
    return self.project_name

def file_path(self):
    return re.search(re.search('[^\s]+(?=\.zip)', self.file_zip).group(0))

class Photo(models.Model):
    belongs_to=models.ForeignKey(Project)
    img=models.ImageField(upload_to='/home/contact/python_project/all_bugs_will_reveal/'+belongs_to.file_path())
    desc=models.CharField(max_length=255)
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96

1 Answers1

2

You can't refer to fields in a model within that same model's definition, as at the point when the definition is being read the class hasn't been defined yet.

The solution is to use a callable for upload_to - as shown in the documentation, this can be a function that is given the parameters instance and filename, so you can call instance.filepath() to get the correct path.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I am trying you follow your instructions but; either i defined the function invalid or i'm not calling it in the right way. `def project_path(instance, filename): return '%s/%s'%(instance.belongs_to.file_path,filename)` and `img=models.ImageField(upload_to=project_path())` returns with `TypeError: project_path() takes exactly 2 arguments (0 given)` – Umur Kontacı Aug 09 '11 at 10:38
  • should be `ImageField(upload_to=project_path)` - without the calling brackets. Otherwise, the function is called when the form is defined, with no parameters, rather than when a file is uploaded. – Daniel Roseman Aug 09 '11 at 10:55
  • Yes, I actually wrote the right code but made a mistake somewhere else and while trying to find the bug, i changed that too. Works well now. Thanks. – Umur Kontacı Aug 09 '11 at 11:04