【问题标题】:Django ImageField is not updating when update() method is used使用 update() 方法时 Django ImageField 不更新
【发布时间】:2019-05-31 02:57:02
【问题描述】:

我正在从 views.py 文件中更新模型中的一些字段。当我使用时,所有其他字段都会正确更新

Profile.objects.filter(id=user_profile.id).update(
        bio=bio,
        city=city,
        date_of_birth=dob,
        profile_pic=profile_pic,
        gender=gender
    )

只是,profile_pic = models.ImageField(blank=True) 没有更新,奇怪的是当我从 admins.py 检查我的Profile 模型时,它显示了我上传的文件名,但我的文件没有显示在我的/media 目录中(我上传所有图片的地方)

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]))

这就是我在 settings.py 中管理媒体文件的方式

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

我认为只有文本存储在 ImageField 中,而 Image 没有上传到 /media 目录 注意:我使用<input type="file" name="profile_pic" class="change_user_img"> 从模板中获取图像

【问题讨论】:

    标签: python django imagefield


    【解决方案1】:

    QuerySet.update() 方法不会在模型上调用save(),因此不会执行将图像放入存储的常用机制。此外,您必须从request.FILES 而不是request.POST 检索上传的图像。

    如果您在模型实例上设置属性然后调用save(),而不是使用update(),则图像应该保存到磁盘上的正确位置。例如:

    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()
    

    如 cmets 中所述,您还必须确保您的表单设置了 enctype="multipart/form-data"

    【讨论】:

    • 代码相同,但出现 AttributeError: 'tuple' object has no attribute '_committed' 的错误。 你能看看我的问题link。我的模型没有保存方法,猜想它会继承自models.Model。我们需要一个 QuerySet 对象来使用 save 方法吗?
    【解决方案2】:

    profile_pic = ... 上指定upload_toDocs here

    【讨论】:

    • 默认情况下,我将 settings.py 配置为将所有图像存储在 /media 目录中......
    • 你是如何定义 MEDIA_ROOT 的?docs.djangoproject.com/en/2.1/ref/models/fields/…
    • 更新媒体根有问题...@Dan Swain
    • BASE_DIR 是否定义如下? PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) BASE_DIR = os.path.dirname(PROJECT_DIR)
    • 你的
      标签上有 enctype="multipart/form-data" 吗?
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2015-04-18
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    相关资源
    最近更新 更多