这可能是一个愚蠢的问题,但我被困住了.
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中保存图像/文件?
发布评论