1

我在 Django 站点中阅读了一些文档,例如:Basic file uploadsFileField.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})
4

1 回答 1

0

我相信如果您将上传表单创建为模型表单,然后将其保存在视图中,它将具有将文件保存到文件系统和模型路径的效果。这是一个基本示例,但我认为它应该有效。

# forms.py
class UploadFileForm(forms.ModelForm):
    class Meta:
        model = models.Image

# views.py
...
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
    form.save()
    return HttpResponseRedirect('/success/url/')
于 2011-10-26T05:22:17.270 回答