6

我希望能够使用 CreateView 和 ModelForm 上传图像文件,但我无法让它工作 - 在选择文件后,表单似乎没有绑定任何文件数据。这是视图的当前内容:

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)

任何人都可以帮忙吗?一个基于类的图像上传视图的简单示例将不胜感激。

4

1 回答 1

19

上传的文件存储在 中request.FILES,而不是request.POST. 并且不要忘记添加enctype="multipart/form-data"到您的<form>标签中。

而且我认为form_valid方法是用于验证,而不是用于保存数据,不是吗?

于 2012-05-29T10:50:43.463 回答