Reputation: 533
I want to create a method inside a model which can be called on a parameter of an attribute to populate it. I thought of doing it this way but it gives me an error NameError: name 'self' is not defined
.
class Host(User):
class Meta:
verbose_name = "Host"
verbose_name_plural = "Hosts"
def gen_path(self):
path = 'static/{userdir}'.format(userdir=self.email)
os.mkdir(path)
return path
hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=self.gen_path(), null=True)
What could be a workaround for this?
Upvotes: 0
Views: 55
Reputation: 1714
You can create method that takes instance
and filename
as parameter for upload_to
attribute;
def gen_path(instance, filename):
extension = filename.split(".")[-1]
filename = f"{instance.email}.{extension}"
return f"static/{filename}"
class Host(User):
hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=gen_path, null=True)
class Meta:
verbose_name = "Host"
verbose_name_plural = "Hosts"
for more information see docs
Upvotes: 1
Reputation:
Try to use this :
You should insert a folder name to save images like :-
hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to='hostimages', null=True)
Upvotes: 0