问题描述
我只是无法弄清楚如何在django中上传图像。我在这里阅读了几十个博客文章和问题,但大多数人只是混淆了我。
I just can't figure out how to upload images in django. I've read dozens of blog posts and questions here, but most of them just confuse me more.
这是我到目前为止。这是我的模型:
Here is what I have so far. This is my model:
class Post(models.Model):
user = models.ForeignKey(User)
screenshot = models.ImageField(null=True, upload_to="images")
date = models.DateTimeField("date posted", auto_now=True)
text = models.TextField()
这是我使用的表单:
class PostForm(forms.Form):
text = forms.CharField(
widget = forms.Textarea(attrs = {'cols': 40, 'rows': 10}), required=True)
screenshot = forms.ImageField(required=False)
这里是我当前如何处理表单:
And here is how I currently process the form:
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = Post(
user = request.user,
text=form.cleaned_data['text'],
screenshot=form.cleaned_data['screenshot']
)
post.save()
但是这不起作用,文件没有上传到服务器。根据,我必须写我自己的handle_uploaded_file函数,但该页面不解释:
But this doesn't work, the file is not uploaded to the server. According to the documentation on file uploads, I have to write my own handle_uploaded_file function, but that page doesn't explain:
- 我如何知道在哪里保存上传的文件?
- 如何在多个目录中传播文件?
- 如何防止两个具有相同名称的文件相互覆盖?
- 我分配给我的模型的ImageField有什么价值?
- How do I figure out where to save the uploaded file?
- How do I spread files over multiple directories?
- How do I prevent two files with the same name to overwrite each other?
- What value do I assign to the ImageField of my model?
问题已经解决了一千次...
That seems like those problems have already been solved a thousand times...
推荐答案
最后,原来我的代码是对的,但我的Django版本错了在升级到Django 1.2.1(从1.0.2)之后,我的代码保持不变。
In the end, it turns out my code was right but my Django version was wrong. After I upgraded to Django 1.2.1 (from 1.0.2), my code worked unchanged.
回答我自己的问题
- 图像上传到我指定的upload_to目录,相对于settings.py中指定的MEDIA_ROOT
- 仍然不确定这个
- Django自动为文件名添加下划线以防止重复
- 分配
screenshot = form.cleaned_data ['screenshot']
像上面的代码一样按照预期工作。
- The images get uploaded to the upload_to dir I specified, relative to the MEDIA_ROOT specified in settings.py
- Still not sure about this one
- Django automatically adds underscores to the file name to prevent duplicates
- assigning
screenshot=form.cleaned_data['screenshot']
like in the code above works as expected.
这篇关于Django图像文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!