Python | Understanding FileField in Django models

In this tutorial, we are going to learn about the FileField in Django models– its use and arguments usability.

Django is an MVT ( Model View Template) framework of Python.

Creating Django Models– This tutorial will help you create various models in Django.

Django FileField Model

FileField model uploads files and documents in Django.

On declaration, FileField accesses an instance of the class FieldFile in Django. This instance proved various methods to store and upload files in Django.

class FileField(upload_to=None, max_length=100, **options)

The FileField has two arguments:

  1. upload_to
  2. max_length

upload_to in Django

It sets the path of the file or the directory that we upload. It accepts the path of the file or the directory in string format. This path is passed to the Storage.save() method.

The string value of the path is appended to the MEDIA_ROOT. This is the location on which the files are in the local filesystem.

def callable_upload_funct(instance, filename):
    return 'req_field'.format(instance.user.id, filename)

class MyDjangoModel(models.Model):
    upload = models.FileField(upload_to=callable_upload_funct)

Besides this,  can also use upload_to as a callable by assigning it a function as a value.

The callable function must have two arguments, instance and filename.

  1. instance: It refers to an instance of FileField where the uploaded will be attached.
  2. filename: It has the original name of the file.

max_length in Django

It sets the maximum length of the files that we upload. This is an optional argument therefore, we don’t need to give value to it always. The database stores the instances of FileField varchar variables by default with a maximum length of 100 characters. Hence, we can easily change it by passing a value in the callable function.

Also, head over to ChoiceField in Django to learn about yet another field in Django.

Leave a Reply

Your email address will not be published. Required fields are marked *