Django Ajax修改头像失败

时间:2018-04-30 14:14:34

标签: ajax django django-models django-forms django-views

我尝试使用Django Ajax来修改用户的头像,但它不起作用。没有任何错误信息,只是不起作用。

这是我在模板中的表单:

<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image_upload' %}" target='frameFile'>
<img id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/>
<input type="file" name="image" id="avatarUp" class=""/>
<button  type="submit">Modify Avatar</button>
{% csrf_token %}
</form>

这是我的Ajax:

$("#jsAvatarForm").submit(function(){
    var image = $("#avatarShow").val()

    $.ajax({
        cache: false,
        type: "POST",
        url:"{% url 'users:image_upload' %}",
        data:{'user_pk':{{ user.pk }}, 'image':image},
        async: true,
        beforeSend:function(xhr, settings){
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
        },
        success: function(data) {
            if(data.status == 'fail'){
                if(data.msg == '用户未登录'){
                    window.location.href="login";
                }else{
                    alert(data.msg)
                }
            }else if(data.status == 'success'){
                window.location.reload();//refresh current page.
            }

            },
    });
    return false;

});

这是views.py:

class UploadImageView(LoginRequiredMixin, View):
    def post(self, request):
        user_pk = request.POST.get("user_pk", 0)
        image = request.FILES.get('image')
        user_change = UserProfile()
        user_change.id = user_pk
        user_change.image = image
        user_change.save
        return HttpResponse('ok')

其实我也有一个forms.py,但我不知道如何在ajax中使用它:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['image']

这是我的用户模型,请注意:我已重写了我自己的USER:

class UserProfile(AbstractUser):
    image = models.ImageField(upload_to="image/%Y/%m", default="image/default.png", max_length=100,verbose_name='头像')

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

任何朋友都可以帮忙吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

显然你可以通过js将图像等文件发送到django,这取决于你在问题中发布的内容,我向你展示了一种可以继续进行的方式,还有很多其他方法可以做到这一点。

如果有什么不起作用,请随意发表评论。

$("#jsAvatarForm").submit(function(){
    var form = this;
    // var image = $("#avatarShow").val()  You can not retrieve the image like this
    var formData = new FormData($(form)[0]);
    // Everything inside the html form is serialized in the formData
    // No need to add X-CSRFToken, {% csrf_token %} is inside the form
    formData.append("NEW_KEY","NEW_VALUE"); # In case of further values


    $.ajax({
         url:$(form).attr('action'),
         type:$(form).attr('method'),
         data:formData,
         processData: false,
         contentType: false, //Don't set any content type header
         success: function(){
             // all your stuffs here
             $('#avatarShow').attr('src',data.avatar_url)
         },
         error:function(){
             alert("error");
         }
    });
    return false;
});

Django的

from django.http import JsonResponse

    # codes here
    user_change.image = image
    user_change.save()
    return JsonResponse({'avatar_url':user_change.image.url})

注意:显示呈现此模板的帖子视图