首页 > 解决方案 > 使用 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">&times;</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]

现在,如果我单击提交按钮字段fileprofile并且description应该通过发送POST但是如果我request.POST只查看字段文件和配置文件被发送并且变量file不存在。

我在这里做错了什么?

标签: djangoformsfile-uploadbootstrap-4

解决方案


# This text is here to fill the answer to get to 30 characters minimum
request.FILES

推荐阅读