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

发布于 2024-12-02 16:39:13 字数 1073 浏览 5 评论 0原文

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

forms.py

from django import forms

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

views.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 %}

希望这有足够的信息来获得一些帮助。请让我知道我还能提供什么。谢谢你,我真的很感谢你的帮助。

Right I'm learning how to do a simple image upload form to upload an image to MEDIA_ROOT. The form renders fine, I get no errors, but the file is not showing up in the MEDIA_ROOT directory. If followed the documentation example and can't get it to work and I know it is because I have not understood django file upload handeling properly. So here is my code:

forms.py

from django import forms

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

views.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}))

template file

{% 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 %}

Hopefully that's sufficient info to get some help. Please let me know what else I can provide. Thank you, I really appreciate the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

叶落知秋 2024-12-09 16:39:13

您不需要将其附加到模型,如 Matt S 所说,如果您的表单设置正确,request.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/

您需要的一切都在那里有详细记录。希望这有帮助!

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

来自文档:

大多数时候,您只需将请求中的文件数据传递到
将上传的文件绑定到表单中所述的表单。这会
看起来像:

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()

You don't need to attach it to a model as Matt S states, request.FILES has all the data for the image if your form is set up correctly.

You need to make sure use enctype="multipart/form-data" in your element, as the docs state here: https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files-to-a-form

Aside from that, read the docs about file uploads: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

All you need is well documented there. Hope this helps!

EDIT OP requested more information on File Uploads

From the docs:

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})

And they have an example of how you could write the handle_uploaded_file function:

def handle_uploaded_file(f):
    destination = open('some/file/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
三生一梦 2024-12-09 16:39:13

为了上传您的文件并在 request.FILES 中显示,您的表单必须包含 enctype="multipart/form-data" ,如下所示:

<form action="{% url scvd.views.merchant_image_upload %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.image }}
    <input type="submit" value="Upload" />
</form>

In order to have your files uploaded and shows in request.FILES, your form MUST contain enctype="multipart/form-data" as shown below:

<form action="{% url scvd.views.merchant_image_upload %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.image }}
    <input type="submit" value="Upload" />
</form>
淡水深流 2024-12-09 16:39:13

您需要将其附加到模型(作为 ImageField)因为它目前没有保存在任何地方。现在处理它可能没有任何问题,但在视图返回后它会被丢弃。

没关系,我没有意识到模型是不必要的。

You need to attach it to a model (as an ImageField) as it's not being saved anywhere presently. It may be handled without any issues right now but it gets discarded after the view returns.

Never mind, I didn't realize models were unnecessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文