📜  ImageField – Django 表单

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

ImageField – Django 表单

Django Forms 中的 ImageField 是用于上传图像文件的输入字段。此输入的默认小部件是 ClearableFileInput。它规范化为: 将文件内容和文件名包装到单个对象中的UploadedFile对象。本文围绕如何使用 Django 表单上传图像以及如何将其保存到数据库。
笔记:

  • 当 Django 处理文件上传时,文件数据最终放置在request.FILES中(有关请求对象的更多信息,请参阅请求和响应对象的文档)。
  • 处理文件时,请确保 HTML 表单标签包含 enctype=”multipart/form-data” 属性。

句法

field_name = forms.ImageField(**options)

django表单ImageField解释

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

geeks app的forms.py文件中输入以下代码。

Python3
from django import forms
 
class GeeksForm(forms.Form):
    name = forms.CharField()
    geeks_field = forms.ImageField()


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


Python3
from django.shortcuts import render
from .forms import GeeksForm
 
# Create your views here.
def home_view(request):
    context = {}
    context['form'] = GeeksForm()
    return render( request, "home.html", context)


html
    {% csrf_token %}     {{ form.as_p }}     


Python3
from django.urls import path
 
# importing views from views..py
from .views import home_view
 
urlpatterns = [
    path('', home_view ),
]


Python3
from django.db import models
 
# Create your models here.
class GeeksModel(models.Model):
    title = models.CharField(max_length = 200)
    img = models.ImageField(upload_to = "images/")
 
    def __str__(self):
        return self.title


Python3
from django.shortcuts import render
from .forms import GeeksForm
from .models import GeeksModel
 
# Create your views here.
def home_view(request):
    context = {}
    if request.method == "POST":
        form = GeeksForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            img = form.cleaned_data.get("geeks_field")
            obj = GeeksModel.objects.create(
                                 title = name,
                                 img = img
                                 )
            obj.save()
            print(obj)
    else:
        form = GeeksForm()
    context['form']= form
    return render(request, "home.html", context)


将极客应用添加到 INSTALLED_APPS

Python3

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

现在要将这个表单渲染到一个视图中,我们需要一个视图和一个映射到该 URL 的 URL。我们先在geeks app的views.py中创建一个视图,

Python3

from django.shortcuts import render
from .forms import GeeksForm
 
# Create your views here.
def home_view(request):
    context = {}
    context['form'] = GeeksForm()
    return render( request, "home.html", context)

在这里,我们从 forms.py 导入该特定表单并在视图中创建它的对象,以便可以在模板中呈现它。
现在,要启动一个 Django 表单,您需要创建 home.html,在其中可以根据需要设计内容。让我们在 home.html 中创建一个表单。

html

    {% csrf_token %}     {{ form.as_p }}     

最后,在 urls.py 中映射到该视图的 URL

Python3

from django.urls import path
 
# importing views from views..py
from .views import home_view
 
urlpatterns = [
    path('', home_view ),
]

让我们运行服务器并检查实际发生了什么,运行

Python manage.py runserver

django-forms-imagefield

因此,通过将“_”替换为“”来创建 geeks_field ImageField 。它是从用户输入图像文件的字段。

如何使用 ImageField – Django Forms 上传文件?

ImageField 用于在数据库中输入图像文件。可以输入Email Id等。到目前为止,我们已经讨论了如何实现ImageField,但是如何在视图中使用它来执行逻辑部分。为了执行一些逻辑,我们需要将输入到字段中的值放入Python字符串实例中。
ImageField 与其他字段不同,需要妥善处理。如上所述,从 ImageField 获取的数据将存储在request.FILES对象中。让我们在 Django 模型中创建一个 ImageField 来演示使用数据库中的表单保存图像。要获取从 github 上传文件的工作代码,请单击此处。
在models.py中,

Python3

from django.db import models
 
# Create your models here.
class GeeksModel(models.Model):
    title = models.CharField(max_length = 200)
    img = models.ImageField(upload_to = "images/")
 
    def __str__(self):
        return self.title

在views.py中,

Python3

from django.shortcuts import render
from .forms import GeeksForm
from .models import GeeksModel
 
# Create your views here.
def home_view(request):
    context = {}
    if request.method == "POST":
        form = GeeksForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            img = form.cleaned_data.get("geeks_field")
            obj = GeeksModel.objects.create(
                                 title = name,
                                 img = img
                                 )
            obj.save()
            print(obj)
    else:
        form = GeeksForm()
    context['form']= form
    return render(request, "home.html", context)

让我们解释一下这段代码的作用,这段代码将用户上传的文件保存在 GeeksModel ImageField 数据库中。每当上传文件时,都会将其保存到 request.FILES 对象中,键为字段名称。所以我们创建了一个模型来保存用户上传的图像。现在让我们尝试将图像文件保存到数据库中。

django-forms-imagefield-2

它已成功加载,文件保存在极客应用程序的 GeeksModel 中。打印了上面的对象,因此创建了 obj 的实例。

django-forms-imagefield-3

核心字段参数

核心字段参数是赋予每个字段以应用某些约束或将特定特征赋予特定字段的参数。例如,向 ImageField 添加参数 required = False 将使用户可以将其留空。每个 Field 类构造函数至少采用这些参数。一些 Field 类采用额外的、特定于字段的参数,但应始终接受以下参数:

Field OptionsDescription
requiredBy default, each Field class assumes the value is required, so to make it not required you need to set required=False
labelThe label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form.
label_suffixThe label_suffix argument lets you override the form’s label_suffix on a per-field basis.
widgetThe widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information.
help_textThe help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. 
 
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.
validatorsThe validators argument lets you provide a list of validation functions for this field. 
 
localizeThe localize argument enables the localization of form data input, as well as the rendered output.
disabled.The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users.