django - 使用 Django 和 Bootstrap 上传文件不起作用
问题描述
我正在使用自动生成的引导表单来允许用户将文件上传到数据库。表单是在这样的模态中生成的:
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Dateien hinzufügen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
{% bootstrap_form form %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn btn-primary">OK</button>
</div>
</form>
</div>
</div>
</div>
使用如下所示的 Django 表单和文件结构:
import django.forms as forms
from .models import StandaloneFile
# Create the form class.
class StandaloneFileForm(forms.ModelForm):
file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = StandaloneFile
fields = ['file', 'profile', 'description']
和
from django.db import models
# Create your models here.
def file_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/<profile.abbr>/<filename>
return '{0}/{1}'.format(instance.profile.abbr, filename)
class StandaloneFile(models.Model):
file = models.FileField(upload_to=file_directory_path)
profile = models.ForeignKey('MeasurementProfile',on_delete=models.SET_NULL,null=True)
description = models.TextField()
date_uploaded = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.file.name.split("/")[-1]
现在,如果我单击提交按钮字段file
,profile
并且description
应该通过发送POST
但是如果我request.POST
只查看字段文件和配置文件被发送并且变量file
不存在。
我在这里做错了什么?
解决方案
# This text is here to fill the answer to get to 30 characters minimum
request.FILES
推荐阅读
- django-forms - Summernote 使用带有 HTML 标记的 Django 表单显示
- android-fragments - AndroidX 中的自定义 ListPreference
- javascript - 赋值给常量变量异常
- sql - SQL 不能在 CASE 条件下使用 AVG
- sql-server - 有没有办法获取变量的值,其名称包含在另一个变量中
- spring - 如何编写断言以确保为 AOP spring 类捕获我的异常
- xslt - 如何告诉 XSLT 脚本绕过特定文本?
- formatting - 如何逃避双破折号——在 DokuWiki
- python - 使用 pandas pivot_table 方法的 IndexError
- python - 以偏序树为优先队列的 Dijkstra 最短路径算法