Image loading and view based on CreateView

I want to be able to upload an image file using CreateView and ModelForm, but I cannot get it to work - it seems that the form does not bind the file data after selecting the file. Here is the current contents of the view:

class AddContentForm(forms.ModelForm):
    class Meta:
        model = Media


class AddContentView(CreateView):
    template_name = 'simple_admin/add_content.html'
    form_class = AddContentForm

    def get_success_url(self):
        return u'/opettajat/subcategory/{0}/{1}/'.format(self.kwargs['subcat_name'].decode('utf-8'), self.kwargs['subcat_id'].decode('utf-8'))


    def form_valid(self, form):
        isvalid = super(AddContentView, self).form_valid(form)
        s = Subcategory.objects.get(pk=self.kwargs['subcat_id'].encode('utf-8'))
        if self.request.POST.get('image'):
            image = form.cleaned_data['image']
            title = form.cleaned_data['art_title'].encode('utf-8')
            year_of_creation = form.cleaned_data['year_of_creation']
            m = Media.objects.get_or_create(image=image, art_title=title, year_of_creation=year_of_creation)[0]
            s.media.add(m)
            s.save()
       return isvalid

    def get_context_data(self, **kwargs):
        context = super(AddContentView, self).get_context_data(**kwargs)
        context['subcategory_name'] = self.kwargs['subcat_name'].encode('utf-8')
        context['subcategory_id'] = self.kwargs['subcat_id'].encode('utf-8')
        return context

     @method_decorator(login_required)
     def dispatch(self, request, *args, **kwargs):
        return super(AddContentView, self).dispatch(request, *args, **kwargs)

Can anyone help? A simple example of a class-based image loading view will be appreciated.

+5
source share
1 answer

Uploaded files are stored in request.FILES, not in request.POST. And don't forget to add enctype="multipart/form-data"to the tag <form>.

And I think the method form_validis for checking, not for saving data, right?

+17
source

All Articles