📜  FilePathField – Django 表单

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

FilePathField – Django 表单

Django Forms 中的 FilePathField 是一个字符串字段,用于从服务器输入特定文件的路径。它用于选择来自用户的输入。需要指定应在 FilePathField 中使用哪些文件夹,并且字段以选择字段的形式显示输入。此输入的默认小部件是 Select。
FilePathField 具有以下必需和可选参数:

  • 路径:-要列出其内容的目录的绝对路径。该目录必须存在。
  • recursive :-如果为 False(默认值),则仅提供 path 的直接内容作为选择。如果为 True,则目录将递归下降,所有后代将被列为选择。
  • match :-正则表达式模式;只有名称与此表达式匹配的文件才会被允许作为选择。
  • 允许文件:-可选。真或假。默认为真。指定是否应包含指定位置的文件。 this 或 allow_folders 必须为 True。
  • allow_folders :-可选。真或假。默认为假。指定是否应包括指定位置的文件夹。 this 或 allow_files 必须为 True。

句法

field_name = forms.FilePathField(**options)

django表单文件路径字段说明

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

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

Python3
from django import forms
 
 
class GeeksForm(forms.Form):
    name = forms.CharField()
    geeks_field = forms.FilePathField(path = "geeksforgeeks/")


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.shortcuts import render
from .forms import GeeksForm
 
# Create your views here.
def home_view(request):
    context ={}
    form = GeeksForm()
    context['form']= form
    if request.POST:
        temp = request.POST
        print(temp)
    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-filepathfield-forms

因此,通过将“_”替换为“”来创建 geeks_field FilePathField 。这是一个输入用户文件路径的字段。

如何使用 FilePathField ?

FilePathField 用于输入数据库中文件的路径。可以从特定文件夹等输入文件。到目前为止,我们已经讨论了如何实现 FilePathField,但是如何在视图中使用它来执行逻辑部分。为了执行一些逻辑,我们需要将输入到字段中的值放入Python字符串实例中。
在views.py中,

Python3

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

作为一个选择字段,它只接受选择输入,否则将看到验证错误。现在让我们尝试从该字段中选择一个选项。

django-forms-filepathfield

可以使用相应的请求字典获取日期数据。如果方法是 GET,则数据将在request.GET中可用,如果是 post,则相应的request.POST 。在上面的示例中,我们有 temp 中的值,我们可以将其用于任何目的。

django-forms-filepathfield-3

核心字段参数

核心字段参数是赋予每个字段以应用某些约束或将特定特征赋予特定字段的参数。例如,向 FilePathField 添加参数 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.