正在上传图片文件

时间:2009-07-03 10:34:19

标签: django file-upload image-upload

你能帮我把图片上传工作在django表格的视图上吗?

Models.py

class User_Profile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile')
    photo  = models.ImageField(upload_to = 'profiles/', null=True, blank=True)

Forms.py

class ProfileForm(forms.ModelForm):
        class Meta:
            model = User_Profile
            exclude = ('user')

Views.py

    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, instance=request.user.profile)

        if profile_form.is_valid():
            profile_form.save()
            return HttpResponseRedirect('/panel/correct/')

    else:
        profile_form = ProfileForm(instance=request.user.profile)

我的html表单已包含enctype="multipart/form-data"

3 个答案:

答案 0 :(得分:16)

您似乎不是binding the file data to the form

profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) 

答案 1 :(得分:7)

为什么不使用django-avatar项目(我假设您正在考虑根据示例添加用户头像到您的项目中)?

他们有一个非常整洁的解决方案,带有额外的标签,可以在第一次显示之前调整图像大小。您可以存储原始图像并定义您希望在网站上接受的图像尺寸,其余部分将自动为您完成。

答案 2 :(得分:3)

这只是关注docs

您没有在帖子中使用正确的表单初始化。特别是您缺少 request.FILES 参数:

 form = ProfileForm(request.POST, request.FILES)

在上面之后,可以从FILES数组中检索上传的文件:

 photo_file = request.FILES['photo']
相关问题