While keeping the Django model instance, in what order are my clean () and save () overrides applied relative to the methods used as ModelField attributes?

I have a model with a field first_name

and last_name

, and they are used to generate a filename on ImageField

. The argument for upload_to

in ImageField

is this method, which generates a filename with this instance information.

When an instance of this model is saved, will calls to .strip()

in be applied clean()

to the fields before they are used to generate the filename? Or will I need to do .strip()

on the data when it is used and also in the clean?

models.py:

def set_path(instance, filename):
    """
    Set the path to be used for images uploaded (trainer photos).
    """
    return u'about/%(first)s_%(last)s.%(ext)s' % {
        'first': instance.first_name.strip(' \t').lower(), #.strip() required?
        'last': instance.last_name.strip(' \t').lower(), #.strip() required?
        'ext': filename.split('.')[-1]
    }

class Trainer(models.Model):
    """
    Trainers and their associated information.
    """
    first_name = models.CharField(max_length=25)
    last_name = models.CharField(max_length=25)
    image = models.ImageField(upload_to=set_path, blank=True, null=True,
        verbose_name="Trainer image")
    description = models.TextField()

    class Meta:
        unique_together = ('first_name', 'last_name',)

    def clean(self):
        super(Trainer, self).clean()
        # Are these calls to .strip() applied before the fields
        # get used as `instance` to determine a filename?
        self.first_name = self.first_name.strip(' \t')
        self.last_name = self.last_name.strip(' \t')
        self.description = self.description.strip(' \t\r\n')

      

+3


source to share


1 answer


If the upload_to argument is callable, it is called during the save () method of the model base. Save () is called after clean (), of course, so you don't need to highlight () any fields if you've already done so in the clean () method.

You can see where the code is being called on line 85 of the Django source: https://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py



generate_filename

is a stored variable indicating what you passed to upload_to.

So the order is form submit -> model.full_clean () -> overridden clean () -> save () which calls upload_to ()

+3


source







All Articles