Posted 21-Sep-2020 | 133 | Django

Django FileField with upload_to determined at runtime

I'm trying to set up my uploads path so that if a user named robin uploads a file. Then it should go to the MEDIA_ROOT/user/robin. However the uploaded files go to MEDIA_ROOT by default. I dont know actually how to do this, i guess we can use models for this but dont know the exact way. Here is how it currently looks:

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

I want to replace the '.' to the user username. I am kind of lost in this as how i can get the user data in upload_to! Any help will be appreciated!