【发布时间】:2014-06-07 22:36:51
【问题描述】:
我正在编写我的第一个使用 ImageField 的 django 应用程序,我正在 困难。问题是我的图片没有上传。我看过 我能找到尽可能多的例子。而且我不确定这里出了什么问题。
我正在尝试通过查看位置来验证我的照片是否正在上传
upload_to 目录。当表单显示在网页中时
显示正确的上传文件按钮。当我点击提交时,下面的代码执行,
但从未上传任何图像。
基于upload_to,我希望看到上传的图片以查看以下任一图片:
myproject/photos 或 myproject/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' )
【问题讨论】: