当我上传文件时,我得到一个" POST / submit / HTTP / 1.1" 200 604.当我检查上传的文件是否无法找到时。
设置文件包括:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
型号:
from django.db import models
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
形式:
from django import forms
from mysite.uploads.models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['description', 'document']
查看:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from mysite.uploads.models import Document
from mysite.uploads.forms import DocumentForm
def model_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect(reverse('uploadindex'))
else:
form = DocumentForm()
return render(request, 'uploads/index.html', {
'form': form
})
的url:
from django.conf.urls import url
from mysite.uploads import views
urlpatterns = [
url(r'^$', views.model_upload, name='uploadindex'),
]
模板:我使用的是multipart / form-data,不确定文件上传的原因。
<html>
<body>
<form action="{% url "uploadindex" %}"
method="post"encytpe="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
答案 0 :(得分:2)
我的猜测是您的DocumentForm无效,并且您在document
字段上收到错误但未在模板中呈现任何反馈以表明此情况。
检查您是否在表单标记上设置了适当的编码。这是通过Django表单处理文件上传的最常见问题:
请注意,如果请求方法是POST,则request.FILES将仅包含数据,并且发布请求的请求具有属性enctype =&#34; multipart / form-data&#34;
https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#basic-file-uploads
答案 1 :(得分:0)
...
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect(reverse('uploadindex'))
else:
print form.errors
...
如果您的document
字段有任何错误,它会显示错误。