我使用ImageField保存上传的图像。代码如下:
//view
class UploadImageView(View):
def post(self,request):
image_form = UploadImageForm(
request.POST, request.FILES, instance=request.user)
if image_form.is_valid():
image_form.save()
return JsonResponse({"status":"success","message":"头像修改成功","icon":"6"})
else:
return JsonResponse({"status": "fail", "message": "请尝试重新上传","icon":"5"})
//model
image = models.ImageField(
upload_to="image/%Y/%m",
# upload_to="image",
default=u"image/default.png",
max_length=100,
verbose_name=u"头像"
)
//form
class UploadImageForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['image']
//html
<div class="layui-col-md3 layui-col-xs12 user_right">
<div class="layui-upload-list">
<img src="{{ MEDIA_URL }}{{ request.user.image }}" name="image" class="layui-circle" id="adminFace">
</div>
<button type="button" class="layui-btn layui-btn-primary userFaceBtn"><i class="layui-icon"></i> 更换头像</button>
</div>
//js, use a frame named layui
upload.render({
elem: '.userFaceBtn',
accept:'images',
url: '/accounts/image/upload/',
//Preview local files
before:function(obj){
obj.preview(function(index,file,result){
$('#adminFace').attr('src',result);
});
//add csrf parameter
var data = {};
data.csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").attr("value");
this.data=data;
},
done: function(res, index, upload){
return layer.msg(res.message,{icon: res.icon,time: 2000});
},
error:function(obj){
}
});
请求是: enter image description here enter image description here 但是它没有得到图像并且有效性是真实的: enter image description here
我刚刚说过学习Django,但并不熟悉。 希望得到您的帮助。非常感谢。