【问题标题】:Cannot upload an image in django using ImageField无法使用 ImageField 在 django 中上传图像
【发布时间】:2014-06-07 22:36:51
【问题描述】:

我正在编写我的第一个使用 ImageField 的 django 应用程序,我正在 困难。问题是我的图片没有上传。我看过 我能找到尽可能多的例子。而且我不确定这里出了什么问题。

我正在尝试通过查看位置来验证我的照片是否正在上传 upload_to 目录。当表单显示在网页中时 显示正确的上传文件按钮。当我点击提交时,下面的代码执行, 但从未上传任何图像。

基于upload_to,我希望看到上传的图片以查看以下任一图片: myproject/photosmyproject/media/photos 正确吗?

我在这里做任何明显的错误吗?如何让我的图片上传?

-------------settings.py-------------

MEDIA_ROOT = '/home/me/django_projects/myproject/media/'
MEDIA_URL = '/media/'

-------------model.py-------------

class Person(models.Model):
    lastName = models.CharField(max_length=20)
    firstName = models.CharField(max_length=20)
    image = models.ImageField(upload_to='photos', blank=True, null=True)

    #  save executes but no image is saved.
    #  Because images are uploaded along with a new entry, I needed a special
    #  work around to get the self.id
    def save(self):
        for field in self._meta.fields:
            if field.name == 'image':
               if self.id is not None:
                 #save image now
                 field.upload_to = 'photos/%d' % self.id
               else:
                 #Save image later
                 saveImageLast = True
        super(Customer, self).save()  # should create self.id if not already
        if saveImageLast == True:
            field.upload_to = 'photos/%d' % self.id
            super(Customer, self).save()
            print "save complete"  #prints, but no image ...?

-------------forms.py----------

class PersonForm(ModelForm):

  class Meta:
      model = Person
      fields = ( 'lastName', 'firstName', 'image' )

【问题讨论】:

    标签: django image


    【解决方案1】:

    来自 django 文档,我认为这会有所帮助(过去这对我有帮助):

    首先,为了上传文件,您需要确保您的 元素正确地将 enctype 定义为“multipart/form-data”

    <form enctype="multipart/form-data" method="post" action="/foo/">
    

    【讨论】:

    • 我确保我的表单包含 enctype 作为“multipart/form-data”。但是还是没有上传。 :(
    【解决方案2】:

    在您使用发布数据创建表单实例的视图中,确保您提供了 request.FILES

    form = PersonForm(request.POST, request.FILES)
    

    【讨论】:

      【解决方案3】:

      这有点晚了,但 'upload_to' 不是一种方法。它是一个属性,表示您的 MEDIA_ROOT 的相对路径。如果要将图像保存在文件夹“photos”中,文件名为 self.id,则需要在模型类的顶部创建一个函数。例如:

      class Person(models.Model):
          def file_path(instance):
              return '/'.join(['photos', instance.id])
          image = models.ImageField(upload_to=file_path)
      

      然后,当您实际保存图像时,您会调用:

      person = Person(firstName='hey', lasteName='joe')
      person.image.save(ImageObject.name, ImageObject)
      

      更多关于图像文件对象here

      更多关于upload_to here

      【讨论】:

        猜你喜欢
        • 2018-11-27
        • 2019-09-04
        • 2015-02-22
        • 1970-01-01
        • 2011-05-14
        • 2020-03-03
        • 2013-01-10
        • 2016-04-23
        • 1970-01-01
        相关资源
        最近更新 更多