4

I have a model, course, with an ImageField and FileField so I’d like to create a folder each time the user create a course. I think I can do this before the model is saved so here is my question.

How can I access a model’s fields in a method?

Models.py

Class Course(models.Model):
 Thumbnail = model.ImageField(upload_to=“...”,...)

    def save(self, *args, **kwargd):
        ... #How can I alter here the ImageField parameters?
        super().save(*args, **kwargs)
phoenix
  • 7,988
  • 6
  • 39
  • 45
VicenteC
  • 311
  • 7
  • 26

3 Answers3

5

See here on getting the model's fields.

To get field of an object instance then it should just be as

def save(self, *args, **kwargs):
     #### How can I alter here the ImageField parameters?
     self.Thumbnail = #do whatever you want here
     super().save(*args, **kwargs)

It's not possible to alter field's params in a method. It must only be done in the field definitions because the model must be saved first

alinajafi
  • 594
  • 1
  • 5
  • 6
AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
2

Instance of the models field can be accessed using self like a normal instance variable.

For example in a model class below,

class DummyModel(models.Model):
    key = models.CharField()
    value = models.TextField()

    def save(self, *args, **kwargs):
        value = self.value # self.value is a model field.
        super().save(*args, **kwargs)

In your case, you can access it using self.Thumbnail

Paras Mishra
  • 336
  • 1
  • 9
1

Since it's not possible to modify the model field's parameters before create it, as @azyCrw4282 said in his answer, it's possible to create a directory with the name of the model's instance and upload there the files parsing a function to upload_to

models.py

def upload_to(instance, filename):
    return 'user_course/{0}/{1}'.format(instance.name, filename) #instance.name will be the name of the course


class Course(models.Model):
    name       = model.CharField(...)
    thumbnail  = models.ImageField(upload_to=upload_to, ...)
VicenteC
  • 311
  • 7
  • 26