I want to call for a self function of a model class as such in upload_to:
class Foo(models.Model):
filestack = models.FileField(upload_to=self. gen_save_path)
def gen_save_path(self):
"""
gen_save_path: void -> String
Generates the path as a string for fileStack field.
"""
return "some generated string"
However I am getting NameError: name 'self' is not defined error
filestack is a class attribute and while declaring it you can not use self as there is no object of class (self) yet created, anyway according to django docs upload_to takes two arguments, instance (An instance of the model where the FileField is defined) and filename (The filename that was originally given to the file), so you can set upload_to to such function
def gen_save_path(instance, filename):
"""
gen_save_path: void -> String
Generates the path as a string for fileStack field.
"""
return "some generated string"
class Foo(models.Model):
filestack = models.FileField(upload_to=gen_save_path)
If you wish to include gen_save_path inside the class, you can use a lambda to call self.gen_save_path e.g.
class Foo(models.Model):
filestack = models.FileField(upload_to=lambda self, fname:self.gen_save_path(fname))
def gen_save_path(self, filename):
return "some generated string"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With