我希望能够使用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)
有人可以帮忙吗?一个基于类的图像上传视图的简单示例将不胜感激。
答案 0 :(得分:17)
上传的文件存储在request.FILES
中,而不是request.POST
中。不要忘记将enctype="multipart/form-data"
添加到您的<form>
代码中。
我认为form_valid
方法用于验证,而不是用于数据保存,不是吗?