1๐
โ
I found a way to solve my problem from views here:
Loading Django FileField and ImageFields from the file system
๐คRafa He So
0๐
You need to use instance
instead of self
. self
does not exist in function1
and function2
scope:
def function1(instance, filename):
return os.path.join(instance.uid.username, str(instance.shortname), '.jpg')
def function2(instance):
return os.path.join(MEDIA_ROOT, str(instance.username), 'tmp.jpg')
class MyModel(models.Model):
uid = models.ForeignKey(User)
shortname = models.CharField()
qr = models.FileField(upload_to=function1, default=function2)
You can found docs for FileField.upload_to
here
You get function2() takes exactly 1 argument, (0 given)
because function2
is expecting for instance
param, and if you try to pass uid
like this:
class MyModel(models.Model):
uid = models.ForeignKey(User)
shortname = models.CharField()
qr = models.FileField(upload_to=function1, default=function2(uid))
will raise an error because at this point uid
is a models.ForeignKey
instance. You could try to do this in a pre_save
signal:
def function2(sender, instance, *args, **kwargs):
if not instance.qr:
instance.qr = os.path.join(MEDIA_ROOT, username, 'tmp.jpg')
pre_save.connect(function2, sender=MyModel)
๐คGocht
- Django crispy-forms disable browser's 'Save Password' popup
- Select a Value from Database and Return another Value in Django
- Django test client get returns 404 however works in shell
0๐
You need to be using instance instead of self. Also, function2
will not be being passed an instance.
๐คJared Mackey
Source:stackexchange.com