📜  FileField – Django 模型

📅  最后修改于: 2022-05-13 01:54:59.853000             🧑  作者: Mango

FileField – Django 模型

FileField 是一个文件上传字段。在上传文件之前,需要指定很多设置,以便安全地保存文件并以方便的方式检索文件。此字段的默认表单小部件是 ClearableFileInput。

句法

field_name = models.FileField(upload_to=None, max_length=254, **options)

FileField 有一个可选参数:

FileField.upload_to

该属性提供了一种设置上传目录和文件名的方式,可以通过两种方式设置。在这两种情况下,值都会传递给 Storage.save() 方法。如果您指定一个字符串值,它可能包含 strftime() 格式,它将被文件上传的日期/时间替换(这样上传的文件不会填满给定目录)。例如:

class MyModel(models.Model):
  
    # file will be uploaded to MEDIA_ROOT / uploads
    upload = models.FileField(upload_to ='uploads/')
  
    # or...
    # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30
    upload = models.FileField(upload_to ='uploads/% Y/% m/% d/')

如果您使用默认的 FileSystemStorage,则字符串值将附加到您的MEDIA_ROOT路径,以形成本地文件系统上存储上传文件的位置。如果您使用不同的存储,请查看该存储的文档以了解它如何处理upload_to

upload_to也可以是可调用的,例如函数。这将被调用以获取上传路径,包括文件名。此可调用对象必须接受两个参数并返回要传递给存储系统的 Unix 样式路径(带有正斜杠)。两个论据是:

ArgumentDescription
instanceAn instance of the model where the FileField is defined. More specifically, this is a particular instance where the current file is being attached.
filenameThe filename that was originally given to the file. This may or may not be taken into account when determining the final destination path

例如:

def user_directory_path(instance, filename):
  
    # file will be uploaded to MEDIA_ROOT / user_/
    return 'user_{0}/{1}'.format(instance.user.id, filename)
  
class MyModel(models.Model):
    upload = models.FileField(upload_to = user_directory_path)

Django 模型文件字段说明

使用示例说明 FileField。考虑一个名为geeks的项目,它有一个名为geeksforgeeks的应用程序。

极客应用的models.py文件中输入以下代码。

from django.db import models
from django.db.models import Model
# Create your models here.
  
class GeeksModel(Model):
    geeks_field = models.FileField()

将极客应用添加到INSTALLED_APPS

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'geeks',
]

现在,当我们从终端运行makemigrations命令时,

Python manage.py makemigrations

将在geeks目录中创建一个名为 migrations 的新文件夹,其中包含一个名为0001_initial.py的文件

# Generated by Django 2.2.5 on 2019-09-25 06:00
  
from django.db import migrations, models
  
class Migration(migrations.Migration):
  
    initial = True
  
    dependencies = [
    ]
  
    operations = [
        migrations.CreateModel(
            name ='GeeksModel',
            fields =[
                ('id', 
                  models.AutoField(
                  auto_created = True,
                  primary_key = True,
                  serialize = False, 
                  verbose_name ='ID'
                )),
                ('geeks_field', models.FileField()),
            ],
        ),
    ]

现在运行,

Python manage.py migrate

因此,当您在项目上运行迁移时,会创建一个geeks_field 它是在数据库中存储任何类型文件的字段。

如何使用文件字段?

FileField 用于将文件存储到数据库中。 FileField 中的任何类型的文件都可以。让我们尝试在上面创建的模型中存储图像。

  • 要开始创建模型实例,请使用以下命令创建一个管理员帐户。
    Python manage.py createsuperuser
  • 输入用户名、电子邮件和安全密码。然后在您的浏览器中输入以下 URL。
    http://localhost:8000/admin/

    文件字段-django-models-1

  • 转到Geeks Models前面添加
    django-models-filefield
  • 选择您要上传的文件,然后单击保存。现在让我们在管理服务器中检查它。我们已经创建了 GeeksModel 的一个实例。
    FileField django 模型

字段选项

字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 FileField 添加参数null = True将使其能够在关系数据库中存储该表的空值。
以下是 FileField 可以使用的字段选项和属性。

Field OptionsDescription
NullIf True, Django will store empty values as NULL in the database. Default is False.
BlankIf True, the field is allowed to be blank. Default is False.
db_columnThe name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
DefaultThe default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_keyIf True, this field is the primary key for the model.
editableIf False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messagesThe error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_nameA human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validatorsA list of validators to run for this field. See the validators documentation for more information.
UniqueIf True, this field must be unique throughout the table.