3

尝试简单的图像上传时出现错误:

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

以下是相关代码的片段(如果您需要更多,请告诉我!):

# 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

1 回答 1

6

您收到异常是因为您在 View 类中指定了实现SingleObjectMixin的“模型”属性。但是,您并没有给它一个要渲染的 Photo 模型的实例。

由于您只想创建一张新照片,因此您应该从 View 类中删除模型属性:

# 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']
于 2013-03-28T20:14:37.123 回答