Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

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

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(
        bio=bio,
        city=city,
        date_of_birth=dob,
        profile_pic=profile_pic,
        gender=gender
    )

only, profile_pic = models.ImageField(blank=True) is not updated, Weird thing is when I check my Profile model from admins.py it shows me the file name which I uploaded, But my file is not shown in my /media directory(where I upload my all Images)

views.py

def edit_submit(request):
if request.method == 'POST':
    profile_pic = request.POST.get('profile_pic')
    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)
    Profile.objects.filter(id=user_profile.id).update(
        bio=bio,
        city=city,
        date_of_birth=dob,
        profile_pic=profile_pic,
        gender=gender
    )
    return HttpResponseRedirect(reverse('profile', args=[user_profile.id]))

This is how I manage my media files in settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I think only text is stored in ImageField and Image is not uploded to /media directory Note: I am using <input type="file" name="profile_pic" class="change_user_img"> for getting image from template

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...