Neeraj Kumar
Neeraj Kumar

Reputation: 533

Model method to generate the value for a parameter of an attribute

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

Answers (2)

uedemir
uedemir

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

user15207035
user15207035

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

Related Questions