ImageField – Django 模型
ImageField 是一个 FileField,上传仅限于图像格式。在上传文件之前,需要指定很多设置,以便安全地保存文件并以方便的方式检索文件。此字段的默认表单小部件是 ClearableFileInput。除了可用于 FileField 的特殊属性外,ImageField 还具有高度和宽度属性。
ImageField 需要 Pillow 库。要安装相同的运行,
pip install Pillow
句法
field_name = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
ImageField 具有以下可选参数:
ImageField.upload_to
该属性提供了一种设置上传目录和文件名的方式,可以通过两种方式设置。在这两种情况下,值都会传递给 Storage.save() 方法。如果您指定一个字符串值,它可能包含 strftime() 格式,它将被文件上传的日期/时间替换(这样上传的文件不会填满给定目录)。例如:
class MyModel(models.Model):
# file will be uploaded to MEDIA_ROOT / uploads
upload = models.ImageField(upload_to ='uploads/')
# or...
# file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30
upload = models.ImageField(upload_to ='uploads/% Y/% m/% d/')
如果您使用默认的 FileSystemStorage,则字符串值将附加到您的MEDIA_ROOT
路径,以形成本地文件系统上存储上传文件的位置。如果您使用不同的存储,请查看该存储的文档以了解它如何处理upload_to
。
upload_to
也可以是可调用的,例如函数。这将被调用以获取上传路径,包括文件名。此可调用对象必须接受两个参数并返回要传递给存储系统的 Unix 样式路径(带有正斜杠)。两个论据是:
Argument | Description |
---|---|
instance | An instance of the model where the ImageField is defined. More specifically, this is a particular instance where the current file is being attached. |
filename | The 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.ImageField(upload_to = user_directory_path)
ImageField.height_field
每次保存模型实例时将自动填充图像高度的模型字段的名称。
ImageField.width_field
每次保存模型实例时将自动填充图像宽度的模型字段的名称。
Django模型ImageField解释
使用示例说明 ImageField。考虑一个名为geeks
的项目,它有一个名为geeksforgeeks
的应用程序。
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
在极客应用的models.py
文件中输入以下代码。
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.ImageField()
将极客应用添加到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.ImageField()),
],
),
]
现在运行,
Python manage.py migrate
因此,当您在项目上运行迁移时,会创建一个geeks_field
。它是一个存储有效图像文件的字段。
如何使用 ImageField ?
ImageField 用于将有效的图像文件存储到数据库中。 ImageField 中的任何类型的图像文件都可以。让我们尝试在上面创建的模型中存储图像。
- 要开始创建模型实例,请使用以下命令创建一个管理员帐户。
Python manage.py createsuperuser
- 输入用户名、电子邮件和安全密码。然后在您的浏览器中输入以下 URL。
http://localhost:8000/admin/
- 转到Geeks Models前面添加。
- 选择您要上传的文件,然后单击保存。现在让我们在管理服务器中检查它。我们已经创建了 GeeksModel 的一个实例。
字段选项
字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 ImageField 添加参数null = True
将使其能够将该表的空值存储在关系数据库中。
以下是 ImageField 可以使用的字段选项和属性。
Field Options | Description |
---|---|
Null | If True, Django will store empty values as NULL in the database. Default is False. |
Blank | If True, the field is allowed to be blank. Default is False. |
db_column | The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. |
Default | The 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_text | Extra “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_key | If True, this field is the primary key for the model. |
editable | If 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_messages | The 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_text | Extra “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_name | A 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. |
validators | A list of validators to run for this field. See the validators documentation for more information. |
Unique | If True, this field must be unique throughout the table. |
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。