📜  FilePathField – Django 表单(1)

📅  最后修改于: 2023-12-03 15:30:45.707000             🧑  作者: Mango

FilePathField – Django 表单

在Django表单中,FilePathField类用于在表单中显示文件路径选择器。它允许用户从指定的目录中选择一个文件。

语法
class FilePathField(
    path='',
    match=None,
    recursive=False,
    allow_files=True,
    allow_folders=False,
    **options
)
参数
  • path:(可选)一个字符串,表示用户可以查看和选择的目录路径。如果为空,则将从项目的根目录开始搜索。
  • match: 用于匹配文件名的Unix shell样式模式。
  • recursive: 如果为True,则在子目录中递归查找文件。否则,只查看指定的目录。
  • allow_files: 如果为True,则允许选择文件。
  • allow_folders: 如果为True,则允许选择文件夹。
示例
添加文件路径选择器到表单中
from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FilePathField(path='/var/www/html/', match='*.pdf', recursive=True, allow_folders=False, allow_files=True)
从表单中获取用户选择的文件名
def uploadFile(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            filePath = form.cleaned_data['docfile']
            # Do something with filePath
            return redirect('success-page')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})
Markdown代码片段
# FilePathField – Django 表单

在Django表单中,FilePathField类用于在表单中显示文件路径选择器。它允许用户从指定的目录中选择一个文件。

## 语法

```python
class FilePathField(
    path='',
    match=None,
    recursive=False,
    allow_files=True,
    allow_folders=False,
    **options
)
参数
  • path:(可选)一个字符串,表示用户可以查看和选择的目录路径。如果为空,则将从项目的根目录开始搜索。
  • match: 用于匹配文件名的Unix shell样式模式。
  • recursive: 如果为True,则在子目录中递归查找文件。否则,只查看指定的目录。
  • allow_files: 如果为True,则允许选择文件。
  • allow_folders: 如果为True,则允许选择文件夹。
示例
添加文件路径选择器到表单中
from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FilePathField(path='/var/www/html/', match='*.pdf', recursive=True, allow_folders=False, allow_files=True)
从表单中获取用户选择的文件名
def uploadFile(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            filePath = form.cleaned_data['docfile']
            # Do something with filePath
            return redirect('success-page')
    else:
        form = DocumentForm()
    return render(request, 'upload.html', {'form': form})