正在上传图片文件

Ale*_*tos 9 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)
Run Code Online (Sandbox Code Playgroud)

Forms.py

class ProfileForm(forms.ModelForm):
        class Meta:
            model = User_Profile
            exclude = ('user')
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*man 16

您似乎没有将文件数据绑定到表单.

profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) 
Run Code Online (Sandbox Code Playgroud)


mic*_*huk 7

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

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