我在 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})