Search code examples
djangomodelsfilefieldimagefield

How to change upload_to parameter of ImageField based on field name in Django?


I would like to upload images to the media root based on the field values given by the Django admin user. Here is the code that I've written and I know that the upload_to parameter is causing the problem. But I don't know how to make it work.

models.py

class Info(models.Model):
    file_no = models.CharField(max_length=100)
    date = models.DateField()
    area = models.IntegerField(default=0.00)
    mouja = models.CharField(max_length=100)
    doc_type_choices = (
            ('deed', 'Deed'),
            ('khotian', 'Khotian'),
        )
    doc_type = models.CharField(max_length=50,
                                choices=doc_type_choices,
                                default='deed')
    doc_no = models.CharField(max_length=50)

    def __unicode__(self):
        return self.file_no

class Image(models.Model):
    info = models.ForeignKey('Info')
    content = models.ImageField(upload_to=self.info.mouja/self.info.doc_type)

    def __unicode__(self):
        return self.info.file_no

Whenever I run python manage.py makemigrations it shows NameError: name 'self' is not defined Thanks in advance for any help!


Solution

  • In the upload_to keyword you would need to provide a function that you will define, for instance:

    def path_file_name(instance, filename):
        return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename)))
    
    class Image(models.Model):
        content = models.ImageField(upload_to=path_file_name)
    

    From Django documentation: Model field reference:

    This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system.

    Within this callable, which in the particular case is path_file_name function, we build a path from the instance field which is the particular record of Image model.

    The filter function removes any None items out of the list and the join function constructs the path by joining all list items with /.