我正在尝试构建多个图片上传器,它连接到我网站上的帖子/列表。我能够设置所有内容,但是当我点击上传时,表单未验证且照片未被保存。 这就是我现在所拥有的。
models.py
class UploadFileModel(models.Model):
# listing = models.ForeignKey(Listing, blank=False, default=1)
file = models.ImageField(upload_to=settings.MEDIA_ROOT)
forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = UploadFileModel
fields = ["file",]
views.py
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
@require_POST
def upload(request, id):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print request.FILES
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponse(status=201)
else:
# print form.errors
return HttpResponse(status=400)
return HttpResponse(status=404)
def photo_upload(request, id):
listing = get_object_or_404(Listing, id=id)
context = {"listing": listing,}
return render(request, "dropzone_photo.html", context)
最后这里是模板的一部分:
<form class="dropzone" id="my-awesome-dropzone" enctype="multipart/form-data">{% csrf_token %}
<div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->
<input type="hidden" name="listing" value="{{ listing.id }}" id="listing_id"/>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
我使用Dropzone.options.myAwesomeDropzone进行以下配置:
url: "/dropzone/upload/" + $("#listing_id").val(),
autoProcessQueue: false,
uploadMultiple: true,
答案 0 :(得分:0)
你真的不需要这里的Django表格。使用此我的观点:
@require_POST
def upload(request, id):
if request.method == "POST" and request.is_ajax():
for filename, uploaded_file in request.FILES.iteritems():
image = UploadFileModel()
image.file = uploaded_file
image.save()
return HttpResponse(status=201)
return HttpResponse(status=404)
这不会起作用:
file = models.ImageField(upload_to=settings.MEDIA_ROOT)
您需要提供上传目录的名称,并且Django将为MEDIA_ROOT添加该名称。例如:
file = models.ImageField(upload_to="uploads")
然后路径&#34; / media / uploads /..."如果您的MEDIA_ROOT是&#34;媒体&#34;。
答案 1 :(得分:0)
所以最后这就是我要找的东西: model.py
class UploadFileModel(models.Model):
listing = models.ForeignKey(Listing, blank=False)
file = models.ImageField(upload_to="uploads")
view.py
@require_POST
def upload(request, id):
if request.method == "POST" and request.is_ajax():
for filename, uploaded_file in request.FILES.iteritems():
print uploaded_file
image = UploadFileModel()
image.file = uploaded_file
listing_instance = Listing.objects.get(id=id)
image.listing = listing_instance
image.save()
return HttpResponse(status=201)
return HttpResponse(status=404)
def photo_upload(request, id):
listing = get_object_or_404(Listing, id=id)
context = {"listing": listing,}
return render(request, "dropzone_photo.html", context)
和模板就像我的问题一样。