Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make use of the file field in django

what else do I need to add to that "file = models.FileField()"

this is what I have done but am still not getting any results, why that?

    class Course(models.Model):

        TOPIC_CHOICES = (
            ("History", "History"),
            ("Chemistry", "Chemistry"),
            ("Computer", "Computer")
        )

        lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE)
        category = models.CharField(choices=TOPIC_CHOICES, max_length=100)
        topic = models.CharField(max_length=250)
        file = models.FileField()
        date_created = models.DateTimeField(default=datetime.now)

        def __str__(self):
            return f"{self.lecturer}: {self.topic}"
like image 848
Joseph Morakinyo Avatar asked Sep 10 '25 22:09

Joseph Morakinyo


1 Answers

According to Django documentation, FileField takes two optional arguments.

  1. upload_to: Sets the upload directory. The value of this argument can have several types. It can be String, Path, or a callable function. Here is an example:
    upload = models.FileField(upload_to='uploads/')
    If you want to define a function for this argument which returns the upload directory, you have to define it based on Django's specification of such function. The function should have the instance and filename arguments. Here is an example:
def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)
  1. storage: A storage object, or a callable which returns a storage object. This argument is used to specify a storage setting for your file-upload field. This argument enables you to choose the appropriate storage environment at runtime.
from django.conf import settings
from django.db import models
from .storages import MyLocalStorage, MyRemoteStorage


def select_storage():
    return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()


class MyModel(models.Model):
    my_file = models.FileField(storage=select_storage)

Another use-case of this argument is having different storage environments for different types of files.

from django.conf import settings
from django.db import models
from .storages import LargeFilesStorage

class MyModel(models.Model):
    my_file = models.FileField(storage=LargeFilesStorage())

As these arguments are optional, you can instantiate a FileField without them. The default values for these arguments are: upload_to='', storage=None

like image 94
Sina Nabavi Avatar answered Sep 13 '25 12:09

Sina Nabavi