2013-03-28 130 views
2

當嘗試一個簡單的圖片上傳我得到一個錯誤:(!如果你需要更多的,讓我知道)Django的基於類的意見和簡單的圖片上傳

TypeError at /upload/ 
__init__() got an unexpected keyword argument 'instance' 

下面是相關的代碼的snippits :

# Models 

class Photo(models.Model): 
    created_at = models.DateTimeField(auto_now_add=True, editable=False) 
    title = models.CharField(max_length=255) 
    image = models.ImageField(upload_to='photos/'+str(uuid.uuid4())+'/') 

# Views 

class PhotoUploadView(CreateView): 
    model = Photo 
    form_class = PhotoUploadForm 
    template_name = 'upload.html' 
    success_url = '/thanks/' 

# Forms 

class PhotoUploadForm(forms.Form): 
    image = forms.ImageField() 
    title = forms.CharField(max_length=255) 

# Urls 

urlpatterns = patterns('', 
    url(r'^upload/', views.PhotoUploadView.as_view()), 
) 

回答

4

,因爲你已經指定在您的視圖類的「模範」的屬性,它實現了SingleObjectMixin你得到一個例外。然而,你並沒有給它一個你的Photo模型的實例來渲染。

既然你只是想創建一個新的照片,你應該從你的視圖類中刪除模型屬性:

# views.py 
from django.views.generic import CreateView 
from myapp.forms import PhotoUploadModelForm 

class PhotoUploadView(CreateView): 
    form_class = PhotoUploadModelForm 
    template_name = 'upload.html' 
    success_url = '/thanks/' 

並修改表單類從ModelForm繼承:

# forms.py 
from django import forms 
from myapp.models import Photo 

class PhotoUploadModelForm(forms.ModelForm): 

    class Meta: 
     model = Photo 
     fields = ['image', 'title'] 
+0

剛我確定我明白。 上面的代碼屬於models.py文件,我應該從視圖中刪除model = Photo? – moreisee

+0

啊,感謝編輯!說得通。 – moreisee

+0

最佳做法是創建一個forms.py文件,並將所有表單放在那裏。查看更新的答案。 –