Possible Duplicate:
Django FileField with upload_to determined at runtime
I am creating a web application that allows user to store files online, like Dropbox. A user's file is modeled by the model Item:
from django.db import models
from django.contrib.auth.models import User
class Item(models.Model):
# Name of file
name = models.CharField(max_length=200)
# Site user who owns the file
user = models.ForeignKey(User)
# Path to file in database
# Python complains here since "username" is an attribute of the User class, not
# an attribute of ForeignKey.
file = models.FileField(upload_to=(user.username + '/' + name))
Now if you look the upload_to argument to FileField, I want to specify where files are stored in my database. If I have a user "bill" with file "myfile" his file should go under the path "bill/myfile".
To get this string I tried "user.username + '/' + name" but python complains that user doesn't have an attribute username because user isn't a User object: it's a ForeignKey that stores a User. So the question is, how do I get the user object from the ForeignKey within code?
Now regarding Django's database API that won't work because the object has to be saved to the database before I can use the API. This is not the case as I need the data during construction of my Item object.