0

所以,我总是在一个单独的项目中测试新事物,而我用来测试它的例子很有效。但是,尝试将其集成到我的项目中并不能得到我需要的结果。我现在已经花了将近 4 个小时在这上面,但到目前为止还没有。

首先,这是代码:

索引.html

<form id="data" enctype="multipart/form-data">
<div class="col-md-4">
 <label class="file">
 <input type="file" id="file1" name="document" multiple>
 <span class="file-custom">Documents</span>
 <button type="button" onclick="enterdata()">Submit</button>
</div>
</form>
 
<script>
function enterdata(){
 if ($"data")[0].checkValidity(){
  alert('validity success');
  var token = ''{{ csrf_token }};
  alert('csrf generated');
  $.ajax({
     type:'POST',
     url:'/user',
     data: {
      doc1:$('file1').val()
   },
   header: {'X-CSRFToken': token},
   success: function(){
     alert("Added");
     $('#data').trigger("reset");
   }
  })
}else{
  $('data')[0].reportValidity()
  }
}
</script>

视图.py

def testing_data(request):
 if request.method == 'POST':
 doc11 = request.POST['doc1']
 
 request_file = request.FILES['document'] if 'document' in request.FILES else None
        if request_file:
            # save attatched file
            # create a new instance of FileSystemStorage
            fs = FileSystemStorage()
            file = fs.save(request_file.name, request_file)
            # the fileurl variable now contains the url to the file. This can be used to serve the file when needed.
            fileurl = fs.url(file)
 landform.objects.create
 (
   mutdoc=doc11,
 )
return HttpResponse('')

模型.py

class landform(models.Model):
 mutdoc = models.CharField(max_length=255)

网址.py

urlpatterns = [
  path('user', testing_data),
 ]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

设置.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

因此,当前代码正在获取路径并将其放入模型中的 mutdoc 字段中,这没关系,并且我在上面的代码中省略了很多其他字段。但除此之外,当我在另一个项目(没有 Ajax)中独立运行它时,获取文件并将其保存在媒体目录中的代码工作正常。但是在我的项目中,当我在上面的那个视图和 Ajax 中组合它时,除了 Django 创建一个媒体文件夹并将所选文件放入其中之外,其他一切都按预期工作。

浏览了大量其他 SO 线程和博客文章和视频,但仍然无法正常工作。

原来的

html


<form method = 'POST' class="col s12" enctype="multipart/form-data">

        {% csrf_token %}

        {{new_form.as_p}}

    <!--Below is our main file upload input -->
        <input type = "file" name = 'document'>
        <p><button type = "submit" class = "waves-effect waves-light btn">Publish</button></p>
</form>

视图.py

from django.shortcuts import render
from django.core.files.storage import FileSystemStorage

def loadpage(request):
    if request.method == "POST":
        # if the post request has a file under the input name 'document', then save the file.
        request_file = request.FILES['document'] if 'document' in request.FILES else None
        if request_file:
            # save attatched file

            # create a new instance of FileSystemStorage
            fs = FileSystemStorage()
            file = fs.save(request_file.name, request_file)
            # the fileurl variable now contains the url to the file. This can be used to serve the file when needed.
            fileurl = fs.url(file)

    return render(request, "template.html")

网址.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', loadpage)
]
# only in development
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
4

1 回答 1

0

1.替换:

urlpatterns = [
  path('user', testing_data),
 ]

urlpatterns = [
  path('user/', views.testing_data, name='testing_data'),
]

2.这可能是问题所在。尝试这个:

代替:

<input type="file" id="file1" name="document" multiple>

和:

<input type="file" id="file1" name="document" >

我找不到关于是否有multipleinside of<input>是否会迫使您使用request.FILES.getlist('document') 而不是 使用的文档request.FILES['document'],但值得一试。

于 2020-12-01T17:54:36.310 回答