Django ImageField is not updating when update() method is used

前端 未结 2 1526
南方客
南方客 2020-12-21 03:54

I am updating some of fields in model from views.py file. All other fields are updated properly when I use

Profile.objects.filter(id=user_profile.id).update(         


        
2条回答
  •  礼貌的吻别
    2020-12-21 04:18

    The QuerySet.update() method doesn't call save() on the model, and so the usual mechanism that places the image into storage is not executed. In addition, you must retrieve the uploaded image from request.FILES not request.POST.

    Rather than using update(), if you set the attributes on the model instance and then call save(), the image should get saved to the correct place on disk. For example:

    profile_pic = request.FILES.get('profile_pic')  # Use request.FILES
    
    bio = request.POST.get('bio')
    city = request.POST.get('city')
    dob = request.POST.get('dob')
    gender = request.POST.get('gender')
    
    user_profile = Profile.objects.get(user=request.user)
    user_profile.bio = bio
    user_profile.city = city
    user_profile.date_of_birth = dob
    user_profile.profile_pic = profile_pic
    user_profile.gender = gender
    user_profile.save()
    

    As mentioned in the comments, you must also ensure that the your form has enctype="multipart/form-data" set.

提交回复
热议问题