I havent posted a question here before, read mostly.
Im learning Django and got file upload working before . But now i’ve broke it somehow.
request.FILES is empty when im uploading but i can see the filename in 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)
It would be much easier to do what you’re trying to do using ModelForms: