python - 我需要更新特定用户 Django 的图像

标签 python django backend

我需要更新特定用户 Django 的图像。现在,如果我更新特定用户的图像,则所有用户的图像都会更新。有什么解决办法吗?这是我的代码:

models.py

class UserWithImage(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)  
    image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
    def __str__(self):
        return self.user.username

views.py

if 'imagechange' in request.POST and request.FILES['image']:
    image = request.FILES['image']
    fs = FileSystemStorage()
    image_fs = fs.save(image.name, image)
    image_new = UserWithImage.objects.update(image=image_fs)

html页面

    <form  id='myform' enctype="multipart/form-data" method="POST">
        {% csrf_token %}               
        <input type="file" class="settings__background__file" name="image" enctype="multipart/form-data"  id="backgroundimage" placeholder="Upload image">
    <button id="submit-image" name="imagechange" type="submit"> Upload Image </button>
     </form>

最佳答案

是的,您必须过滤您的查询集。您当前正在更新所有对象。

image_new = UserWithImage.objects.filter(user=request.user).update(image=image_fs)

或者如果您不想更新执行请求的用户,您可以这样调用它

user = User.objects.get(id=1)
image_new = UserWithImage.objects.filter(user=user).update(image=image_fs)

关于python - 我需要更新特定用户 Django 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60188968/

相关文章:

backend - 具有用户特定数据的对话流

python - 类型错误 : bytes or ASCII string of length 1 expected in QByteArray?

python - Pandas 系列按月份索引排序

django - 如何在Django中使用基于条件的orderby?

python - 如何在 View 集中获取自定义列表

python - 按日期排序所有信息 DJANGO

python - SSL_CERT_DIR 未由 urllib2 评估

python - 在 python 中跳过初始列表项(或基于项目的分区列表)的更紧凑的方法是什么?

django - 使用 Django factory_boy 进行测试中的用户身份验证

java - 将图像上传到java spring