尝试从Django表单上传图片时出错

时间:2019-06-14 16:38:07

标签: python django upload

我正在尝试从我正在构建的表单中上传图像。

正如我在标题中所述,我的错误是文件未上传。而且我不知道哪里出了错,这是我的models.py:

def upload_location(instance, filename):
    return "uploads/%s/img/%s/" % (instance.id, filename)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    ...
    width_field      = models.IntegerField(default=0)
    height_field     = models.IntegerField(default=0)
    photo            = models.ImageField(
                                        upload_to=upload_location,
                                        null=True, blank=True, 
                                        width_field="width_field", 
                                        height_field="height_field"
                                    )


    USERNAME_FIELD  = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    objects = UserManager()

    ...

问题是“照片”字段。

以下是我称之为的表格:

class UserConfigurationForm(UserChangeForm):

    class Meta:
        model=CustomUser

        fields = (
                    'photo',
                    'password'
                    ...
                 )

我在其中调用表单的模板:

                  <form method="POST">
                    {%csrf_token%}

                    <input type="file" name="photo" accept="image/*">
                    ...

            <!--SUBMIT-->
                      <div class="form-group">
                           <div class="col-xs-12">
                                <br>
                                <button class="btn btn-lg btn-success" type="submit"><i class="glyphicon glyphicon-ok-sign"></i> Guardar cambios</button>
                      </div>
                </form>

最后,这是我的views.py:

def configuration(request):

    form = UserConfigurationForm(request.POST or None, instance=request.user)

    if form.is_valid():

        form.save()
        return redirect('myuser:myuser')

    else:
        form = UserConfigurationForm(instance=request.user)
        return render(request, 'myuser/configuration.html', {'form': form})

因此,如果您能告诉我所有这些错误在哪里,我将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:2)

首先在HTML代码中的添加表单标签中添加以下属性:

enctype="multipart/form-data"

然后,您应该从视图中的表单中获取数据,其中还包括图像数据:

if request.method == 'POST':
    form = UserConfigurationForm(request.POST, request.FILES, request.user)
    if form.is_valid():
        ...
        handle_uploaded_file(request.FILES['photo']) # this will handle you image
        return HttpResponseRedirect('/success/url/')
else:
    ...
return render(request, 'upload.html', {'form': form})

答案 1 :(得分:0)

U忘记了将请求中的文件发送到表单

IntegrationFlow