Django表单上传request.files为空

时间:2011-09-02 19:45:45

标签: django django-forms

我之前没有在这里发过一个问题,主要是阅读。

我正在学习Django并且之前有文件上传工作。但现在我以某种方式打破了它。

request.FILES在我上传时为空,但我可以在request.raw_post_data中看到文件名。

这是html的代码

<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Upload Photo" />
</form

表格

class PhotoUploadForm(forms.Form):
    title = forms.CharField(max_length=50)
    description = forms.CharField(required=False,max_length="254")
    photo = forms.ImageField()

视图

class PhotoUploadView(FormView):

    template_name ="album/photo_upload.html"
    form_class = PhotoUploadForm

    def get_context_data(self,**kwargs):
        context = super(PhotoUploadView,self).get_context_data(**kwargs)
        context['user_info'] = self.request.user
        if 'upload_form' in kwargs:
            context['upload_form'] = kwargs['upload_form']
        else:
            context['upload_form'] = PhotoUploadForm()
        album = get_object_or_404(Album,id=self.kwargs['album_id'])
        context['album'] = album
        context['form'] = self.form_class
        return context

    def post(self,*args,**kwargs):
        print self.request.FILES
        print self.request.raw_post_data
        if self.request.method == "POST":
            form = PhotoUploadForm(self.request.POST,self.request.FILES)
            if form.is_valid():
                photo = Photo()
                photo.title = form.cleaned_data['title']
                photo.summary = form.cleaned_data['description']
                photo.album = get_object_or_404(Album,id = kwargs['album_id'])
                photo.is_cover_photo = True                 
                path = self.generate_filename(self.request.FILES['photo'].name,self.request.user,kwargs['album_id'])
                destination = open(path,"wb+")
                for chunk in self.request.FILES['photo'].chunks():
                    destination.write(chunk)
                destination.close()
                photo.imagePath = path
                photo.save()
        return self.render_to_response(self.get_context_data(upload_form=form)

2 个答案:

答案 0 :(得分:4)

我也是使用FormView做的(我主要是学习如何使用它,django doc用于最新的泛型类视图非常有限);虽然@bezidejni答案可能是一个更好的解决方案,但这就是你如何使它与你的问题一起工作:

class PhotoUploadView(FormView):

    template_name ="album/photo_upload.html"
    form_class = PhotoUploadForm

    def form_valid(self, form):
        """
        This is what's called when the form is valid.
        """
        photo = form.cleaned_data['photo'] # <= this is your uploaded file in memory
        # read your photo object by chunks, save it to disk, or whatever else
        # ....
        # then keep on going! you can make the 'get_success_url' more complex should you need to.
        return HttpResponseRedirect(self.get_success_url())

PS。 如果您使用的是FormView,则不应使用render_to_response;如果您需要将上下文传递给已指定为get_context_data

的模板,请重载template_name

答案 1 :(得分:0)

使用ModelForms做你想做的事情要容易得多:

#forms.py
class PhotoAddForm(forms.ModelForm):
    class Meta:
        model = Photo

    def __init__(self, album_id, *args, **kwargs):
        self.album_id = album_id
        super(PhotoAddForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        photo = super(PhotoAddForm, self).save(commit=False)
        photo.album_id = self.album_id 
        if commit:
            photo.save()
        return photo

#views.py
class AddPhotoView(CreateView):
    form_class = PhotoAddForm
    template_name = 'photos/add_photo.html'

    def get_success_url(self):
        return reverse('photo_add_successful')

    def get_form_kwargs(self):
        kwargs = super(AddPhotoView, self).get_form_kwargs()
        kwargs.update({
            'album_id': self.kwargs['album_id'],
        })
        return kwargs