首页 文章

Django表单上传request.files为空

提问于
浏览
5

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

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

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

here is the code for the html

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

the form

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

the view

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

    使用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
    
  • 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;如果需要将上下文传递给已指定为 template_name 的模板,则重载 get_context_data

相关问题