1π
β
You canβt do it straight away since you cannot pass additional arguments. But you can add user to the instance youβre saving so you can get it by doing instance.user.username
or even instance.username
.
In your creation code you would have something like this:
doc = Document2(random stuff but no docfile2)
doc.username = userName
doc.docfile2 = theFile
doc.save()
π€Wolph
0π
For my puproses I use class with some method for callable and __init__
method for various arguments, such as:
class UploadTo:
def __init__(self, folder = None):
self.folder = folder
def save_path(self, instance, filename):
return f"/path/to/{folder}/{filename}"
Using:
class Document2(models.Model):
docfile2 = models.FileField(upload_to=UploadTo(folder=userName).save_path
Note: this approach will generate new migration every time you run makemigrations
. It changes nothing, but creates new migration file. As for me, I manage this in different ways depend of particular case.
The another approach is to define property or method inside the model itself and then get it from instance
:
class Document2(models.Model):
docfile2 = models.FileField(upload_to=item_uploads_to)
@property
def user_name(self):
return userName
Then this value is reachable from function:
def item_uploads_to(instance, filename):
return '/home/' + instance.user_name + '/path/to/uploads/' + filename
π€Aleksei Trankov
- [Answer]-Django generic UpdateView: Getting the object to be updated
- [Answer]-Django: Matching query does not exist and django.core.exceptions.ImproperlyConfigured
Source:stackexchange.com