如何在Django中保存图像/文件?

编程入门 行业动态 更新时间:2024-10-28 18:28:00
本文介绍了如何在Django中保存图像/文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这可能是一个愚蠢的问题,但我被困住了.

This might be a stupid question but I'm stuck.

我在此处阅读了有关Django中文件/图像上传的文档,但是我不确定如何继续: docs.djangoproject/en/1.2/topics/http/file-uploads/

I read the documentation on file/image uploads in Django here but I'm not sure how to proceed: docs.djangoproject/en/1.2/topics/http/file-uploads/

我的模型定义如下:

class PicUploads(models.Model): blog_post = models.ForeignKey(Post) pic = models.ImageField(upload_to='pics/%Y/%m/%d') class PicUploadsForm(forms.ModelForm): class Meta: model=PicUploads exclude = ('blog_post',)

在我的视图文件中,如何保存图像?

In my views file, how do I go about saving the image?

如果我使用文档中定义的handle_uploaded_file函数,则图像将存储在定义的目录中,但是我该怎么做以将其路径以及外键保存在 PicUploads 模型中?为什么我不能像对文本数据那样仅使用 save()方法?

If I use the handle_uploaded_file function as defined in the documentation, the image gets stored in the defined directory but what do I do to save its path along with the foreign key in the PicUploads model? Why can't I just use the save() method like I do with text data?

推荐答案

save()是您需要在带有 File/ImageField .

您正在查看的文档说明了如何使用一些上传处理程序来自定义默认行为,这不是必需的.

The document you are looking at explains how to use some upload handler to customize the default behavior, it's not required.

只需使用 request.POST 和 request.FILES 实例化您的模型表单,调用 save()即可!

Just instantiate your modelform with request.POST and request.FILES, call save() and all is done!

form = Form(request.POST, request.FILES) if form.is_valid(): form.save()

更多推荐

如何在Django中保存图像/文件?

本文发布于:2023-06-08 14:27:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/583063.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   文件   如何在   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!