使用django表单上传文件

时间:2017-02-22 18:26:09

标签: python django forms

任何人都可以帮我找到我的错误。我是django的新手。我想用表格上传图片。

#forms.py
class ProfileFormSt(forms.Form):
     image_url = forms.FileField(required=False)

#views.py
class UpdateProfileStView(FormView):
    template_name = "home/member_st_form.html"

    def get(self, request, id):
        user = User.objects.get(id=self.kwargs['id'])
        profile = StudentProfile.objects.get(user=user)
        form = ProfileFormSt(initial={
            'image_url': profile.propic,
        })
        return render(request, self.template_name, {'form': form})

    def post(self, request, id):
        user = User.objects.get(id=self.kwargs['id'])
        form = ProfileFormSt(request.POST, request.FILES)
        profile = StudentProfile.objects.get(user=user)
        if request.POST.get('image_url'):
            profile.propic = request.POST.get('image_url')
        profile.save()
        return redirect('home:member-profile-st', id)

#member_st_form.html
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }}
    <button type="submit">update</button>
</form>

#models.py
class StudentProfile(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      propic = models.FileField(default="profile-icon.png")

request.POST.get('image_url')总是返回空...无法找到我做错了...

1 个答案:

答案 0 :(得分:1)

您的image_url是一个文件字段,因此它应该出现在request.FILES

if request.FILES['image_url']:
     profile.propic = request.FILES['image_url']