views:

803

answers:

1

I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='.')

So what I want is instead of '.' as the upload_to, have it be the user's name.

I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.

Thanks for the help!

+13  A: 

You've probably read the documentation, so here's an easy example to make it make sense:

def content_file_name(instance, filename):
    return '/'.join(['content', instance.user.username, filename])

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to=content_file_name)

As you can see, you don't even need to use the filename given - you could override that in your upload_to callable too if you liked.

SmileyChris
That was a perfect example, works great. Was looking at this completely backwards... I'll submit it as an example to the FileField's documentation in Django. Thanks!!
Teebes
Yeah, it probably does belong in docs - it's a reasonably FAQ on IRC
SmileyChris
+1. I was looking for this, thx man.
panchicore
Does this work with ModelForm? I can see that instance has all the attributes of the class model, but there are no values (just a str of the field name). In the template, user is hidden. I may have to submit a question, I have been googling this for hours.
mgag
Yes it works, and yes you should ask a new question (or ask for help on #django irc)
SmileyChris