2011-10-26 83 views
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}) 

回答

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/') 
相關問題