gpt4 book ai didi

django - 简单的 Django 图像上传 - 图像文件不保存

转载 作者:行者123 更新时间:2023-12-05 08:15:10 25 4
gpt4 key购买 nike

对了,我正在学习如何做一个简单的图片上传表单来将图片上传到 MEDIA_ROOT。表单呈现良好,我没有收到任何错误,但该文件未显示在 MEDIA_ROOT 目录中。如果遵循文档示例但无法使其正常工作,我知道这是因为我没有正确理解 django 文件上传处理。所以这是我的代码:

表单.py

from django import forms

class UploadImageForm(forms.Form):
image = forms.ImageField()

View .py

def merchant_image_upload(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
FileUploadHandler(request.FILES['image'])
return HttpResponseRedirect('/dashboard/gallery')
else:
form = UploadImageForm()
return render_to_response('gallery.html', RequestContext(request, {'form': form}))

模板文件

{% extends 'base.html' %}
{% block main %}
<form action="{% url scvd.views.merchant_image_upload %}" method="post">{% csrf_token %}
{{ form.image }}
<input type="submit" value="Upload" />
</form>
{% endblock %}

希望这些信息足以获得一些帮助。请让我知道我还能提供什么。谢谢,非常感谢您的帮助。

最佳答案

您不需要像 Matt S 所说的那样将它附加到模型上,请求。如果您的表单设置正确,FILES 包含图像的所有数据。

您需要确保在您的元素中使用 enctype="multipart/form-data",如此处的文档所述:https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form

除此之外,请阅读有关文件上传的文档:https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

您需要的一切都在那里得到了很好的记录。希望这对您有所帮助!

EDIT OP 请求有关文件上传的更多信息

来自文档:

Most of the time, you'll simply pass the file data from request into the form as described in Binding uploaded files to a form. This would look something like:

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})

他们有一个示例,说明如何编写 handle_uploaded_file 函数:

def handle_uploaded_file(f):
destination = open('some/file/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()

关于django - 简单的 Django 图像上传 - 图像文件不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7303215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com