能不能请你帮我把图像传上工作的观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"

有帮助吗?

解决方案

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

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

其他提示

为什么不使用 Django的头像项目(我假设你正在考虑将用户头像到您的项目的基础上,例如)?

他们有与显示它第一次之前调整图像大小的额外标签的整齐漂亮的解决方案。您存储原始图像,并定义您希望接受网站上的图像大小,其余的为你自动的完成。

这只是问题的以下的 文档.

你不是使用正确的形式的初始化在你的岗位。特别是你失踪 请求。文件 参数:

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

之后,上载的文件可以从中检索文件阵列:

 photo_file = request.FILES['photo']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top