moreisee
moreisee

Reputation: 408

Django Class based views and Simple Image Upload

When trying out a simple image upload I'm getting an error:

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

Here are the snippits of relevant code (If you need more, let me know!):

# 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()),
)

Upvotes: 3

Views: 7480

Answers (1)

Kyle Getrost
Kyle Getrost

Reputation: 737

You're getting an exception because you've specified a "model" attribute in your View class which implements the SingleObjectMixin. However, you're not giving it an instance of your Photo model to render.

Since you just want to create a new photo, you should remove the model attribute from your View class:

# 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/'

And modify your form class to inherit from a ModelForm:

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

class PhotoUploadModelForm(forms.ModelForm):

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

Upvotes: 6

Related Questions