Django图像文件上传

发布于 2024-09-11 15:24:24 字数 1264 浏览 16 评论 0原文

我只是不知道如何在 django 中上传图像。我在这里阅读了数十篇博客文章和问题,但其中大多数只是让我更加困惑。

这是我到目前为止所拥有的。这是我的模型:

 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)

这是我当前处理表单的方式:

  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函数,但该页面没有解释:

  • How do I find out where to save the uploaded file?
  • 如何将文件分布到多个目录?
  • 如何防止两个同名文件互相覆盖?
  • 我应该为模型的 ImageField 分配什么值?

看来这些问题已经被解决了一千次了......

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

Here is the form that I use:

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

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:

  • 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...

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

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

发布评论

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

评论(2

太阳哥哥 2024-09-18 15:24:24

1) 您的 ImageField 需要一个 upload_to 路径:

models.ImageField(required=False, upload_to="/relative/path/to/foo/bar")< /code>

请注意,IIRC,这是相对于您的 MEDIA_ROOT

2)要将它们分布在目录中,只需设置 upload_to=my_path_naming_method 并执行

def my_path_naming_method(instance, filename):
  #something here that returns a new/bespoke string path for each file or similar

3)如果两个文件具有相同的名称,Django 会给出较新的文件一个 _ 后缀。例如 foo.jpg 和 'foo_.jpg' 因此永远不会出现名称冲突

4) 我不明白你的意思,但希望 1-3 能让你顺利进行。

1) Your ImageField needs an upload_to path:

models.ImageField(required=False, upload_to="/relative/path/to/foo/bar")

Note that, IIRC, this is relative to your MEDIA_ROOT

2) For spreading them over directories, just set upload_to=my_path_naming_method and do

def my_path_naming_method(instance, filename):
  #something here that returns a new/bespoke string path for each file or similar

3) If two files have the same name, Django gives the newer one a _ suffix. eg foo.jpg and 'foo_.jpg' so there is never a name collision

4) I don't get what you mean by that, but hopefully 1-3 have got you rolling.

久伴你 2024-09-18 15:24:24

最后,事实证明我的代码是正确的,但我的 Django 版本是错误的。在我升级到 Django 1.2.1(从 1.0.2)后,我的代码工作没有变化。

回答我自己的问题

  • 图像被上传到我指定的 upload_to 目录,相对于 settings.py 中指定的 MEDIA_ROOT
  • 仍然不确定这一点
  • Django 会自动在文件名中添加下划线以防止重复
  • 分配 screenshot=form。 clean_data['screenshot'] 就像上面的代码一样按预期工作。

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.

To answer my own questions

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