我讀過Django網站中的一些文檔,例如:Basic file uploads和FileField.storage。但是,我仍然不明白如何將文件(或圖像)上傳到服務器並將其鏈接存儲在數據庫中。我想將文件寫入以下目錄,例如:'image /%Y /%m /%d'如何上傳圖像並將其鏈接存儲在數據庫中
請給我一個示例代碼。非常感謝。
我的代碼如下爲:
#models.py
class Image(models.Model):
imageid = models.AutoField()
title = models.CharField(max_length=100)
imagepath = models.ImageField(upload_to='images/%Y/%m/%d/')
#forms.py
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=100)
image = forms.FileField()
#views.py
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# How to upload file to folder named 'images/%Y/%m/%d/'
# How to save the link above to database
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})