如何在django中保存模板中的图像

时间:2016-07-04 08:08:04

标签: django-views

我想将图片保存到来自模板的个人资料图片字段,但我无法保存在媒体根目录

class SettingFormView(FormView):
    form_class = ProfileSettingsForm
    template_name = 'profile.html'
    success_url = '/'

    def get_initial(self):
        if self.request.user.is_authenticated():
            profile = Profile.objects.get(user_id__exact=self.request.user.id)
            self.initial['first_name'] = profile.first_name
            self.initial['last_name'] = profile.last_name
            self.initial['fathers_name'] = profile.fathers_name
            self.initial['email'] = profile.email
            self.initial['mobile'] = profile.mobile
            self.initial['entity'] = profile.entity
            self.initial['image'] = profile.image
        return self.initial.copy()

    def form_valid(self, form):
        if self.request.user.is_authenticated():
            form = ProfileSettingsForm(self.request.POST, self.request.FILES)
            user = User.objects.get(username__exact=self.request.user.username)
            if form:
                profile = Profile.objects.get(user_id__exact=self.request.user.id)
                profile.first_name = self.request.POST['first_name']
                profile.last_name = self.request.POST['last_name']
                profile.fathers_name = self.request.POST['fathers_name']
                if user.email != self.request.POST['email']:
                    profile.email = self.request.POST['email']
                    user.email = self.request.POST['email']
                profile.mobile = self.request.POST['mobile']
                profile.entity = self.request.POST['entity']
                profile.image = self.request.POST['image']
                **profile.image.async = self.request.POST['image']**
                profile.save()
                user.save()
                return super(SettingFormView, self).form_valid(form)
        else:
            return redirect('/profile/sign')

我得到以下异常:

  

异常类型:MultiValueDictKeyError异常值:"' image'"

1 个答案:

答案 0 :(得分:0)

上传的文件位于request.FILES,而不是request.POST。 Alos在Documentation开始了。

'普通'版本

f = request.FILES['image']
with open('upload/destination.ext', 'wb+') as dest:
    for chunk in f.chunks():
        dest.write(chunk)

型号版本

Documentation

profile_form = ProfileSettingsForm(request.POST, request.FILES)
    if profile_form.is_valid():
        profile = Profile(image=request.FILES['image'])
        profile.first_name = request.POST.get('first_name')
        # ...
        profile.save()