我在views.py中使用了form_valid(self, form)
來處理和處理我的圖像。完整的代碼是有點長,很具體,但我會後一些snipplets應顯示如何生成的文件名的想法:
def form_valid(self, form):
upload = self.request.FILES['profilbild_original'] #coming from a very simple form
self.request.user.student.profilbild_original = upload
self.request.user.student.save()
#no renaming was required here, but now I did some work:
inputfilepath = os.path.join(my_app.settings.MEDIA_ROOT, profilbild_path(self.request.user, str(upload)))
original = Image.open(inputfilepath)
original.thumbnail((200,200), Image.ANTIALIAS)
filename = str(upload)+'.thumbnail_200_200_aa.jpg'
filepath = profilbild_path(self.request.user, filename)
filepath = os.path.join(my_app.settings.MEDIA_ROOT, filepath)
original.save(filepath, 'JPEG', quality=90)
self.request.user.student.profilbild = profilbild_path(self.request.user, filename).replace("\\", "/")
self.request.user.student.save()
return super(ProfilbildView, self).form_valid(form)
profilbild_path
是根據https://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.upload_to功能:
def profilbild_path(instance, filename):
return os.path.join('profilbilder', str(instance.id), filename)
我希望這給你一些線索。
來源
2013-09-25 15:19:46
OBu
這個答案有幫助嗎?你需要更多信息嗎? – OBu
恐怕它沒有幫助我。我沒有自己的視圖來處理上傳,我正在使用django-filer。我應該在哪裏放置這個form_valid方法? – gwaramadze