django模型不保存上传的图像

时间:2018-10-21 19:38:52

标签: django django-models

我正在尝试上载/更新用户使用django / ajax / jquery上传的图像。我的前端代码似乎正在运行。但是django模型不会上传/保存传递的图像。

这是我的个人资料模型:

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{ self.user.username } Profile'

以及用于更新用户信息的表格:

from django.db import models
from django import forms
from django.contrib.auth.models import User
from .models import Profile


class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username','email']

class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['image']

这是我用于更新图像的视图功能:

@login_required
def update_profile_image(request):
    #print(request.FILES)

    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        print(p_form)

        if p_form.is_valid():
            p_form.save()

            context = {'None': 'none'}
            return JsonResponse(context)
        else:
            return HttpResponse('None')

当我打印p_form时,即在命令窗口上打印的内容:

<tr><th><label for="id_image">Image:</label></th><td>Currently: <a href="/media/profile_pics/profile_pic.jpg">profile_pics/profile_pic.jpg</a><br>
Change:
<input type="file" name="image" accept="image/*" id="id_image"></td></tr>

我已将enctype="multipart/file-data"添加到表单中,所以这不是问题。

这和我所说的ajax调用一样运行正常:

$(document).on('submit', '#profile_edit_form', function(event){

  event.preventDefault();
  //method = $(this).attr('method');

  var img_data = $('#id_image').get(0).files[0];
  formdata = new FormData();
  formdata.append("img_data", img_data);
  console.log(formdata.get("img_data"));

  $.ajax({
      url     : "/users/update_profile_info/",
      type    : 'post',
      dataType: 'json',
      data    : $(this).serialize(),
      success : function(data) {

        $('#profile_name_tag').html(data.username);
        $('#username_navbar').html(data.username);



        $.ajax({
            url         : "/users/update_profile_image/",
            type        : 'POST',
            enctype     : "multipart/form-data",   //it is done inside jquery
            data        : formdata,
            cache       : false,
            contentType : false,
            processData : false,
            success : function(data) {
              console.log('success');
              //$('#profile_picture').html(data.)

            },
            error: function(data) {
              console.log('image-fail');
            }
        });

      },
      error: function(data) {
          console.log('info-fail');
      }
  });


});

希望你们能提供帮助。我迷路了。我已经为此苦苦挣扎了好几天,但仍然不知道问题出在哪里。

谢谢

1 个答案:

答案 0 :(得分:0)

最后大约5天后,我发现了问题所在。 在我的模型中,我拥有“图像”字段。但是在我的ajax调用中,我将其命名为“ img_data”。这就是为什么它没有被保存。

这个问题帮助我发现了: Save method of Django model's instance does not update fields

相关问题