【问题标题】:How to Update ImageField in Django?如何在 Django 中更新 ImageField?
【发布时间】:2020-11-27 14:38:05
【问题描述】:

我是 Django 的新手。我在更新 ImageField 时遇到问题。我有以下代码

在models.py

 class ImageModel(models.Model):
      image_name = models.CharField(max_length=50)
      image_color = models.CharField(max_length=50)
      image_document = models.ImageField(upload_to='product/')

-这是我的表单.py

 class ImageForm(forms.ModelForm):
    class Meta:
        model = ImageModel
        fields = ['image_name', 'image_color' , 'image_document']

在 Html 文件中 (editproduct.html)

<form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}">
       {% csrf_token %}
        <input class="form-control" type="text" name="image_name" value="{{ singleimagedata.image_name}}">
        <input class="form-control" type="file" name="image_document">
        <button type="submit" class="btn btn-primary">UPDATE PRODUCT</button>
</form>

-myapp 是我的应用程序名称。 {{singleimagedata}} 是一个包含所有获取数据的变量

-urls.py

urlpatterns = [
    path('productlist', views.productlist, name='productlist'),
    path('addproduct', views.addproduct, name='addproduct'),
    path('editimage/<int:id>', views.editimage, name='editimage'),
    path('updateimage/<int:id>', views.updateimage, name='updateimage'),
]

这是我的观点.py

def productlist(request):
    if request.method == 'GET':
        imagedata = ImageModel.objects.all()
        return render(request,"product/productlist.html",{'imagedata':imagedata})

def addproduct(request):
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, 'Image Uploaded')
            return redirect('/myapp/productlist')
    else:
        imageform = ImageForm()
        return render(request, "product/addproduct.html", {'imageform': imageform})

def editimage(request, id):
    singleimagedata = ImageModel.objects.get(id=id)
    return render(request, 'product/editproduct.html', {'singleimagedata': singleimagedata})

def updateimage(request, id):  #this function is called when update data
    data = ImageModel.objects.get(id=id)
    form = ImageForm(request.POST,request.FILES,instance = data)
    if form.is_valid():
        form.save()
        return redirect("/myapp/productlist")
    else:
        return render(request, 'demo/editproduct.html', {'singleimagedata': data})
  • 我的图片上传工作正常。更新数据时无法更新图片。其余数据已更新。我不知道如何更新图片以及如何删除旧图片并将新图片放入目录。李>

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    我认为你错过了enctype="multipart/form-data",尝试更改:

    <form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}">
    

    进入;

    <form method="POST" enctype="multipart/form-data" action="{% url 'updateimage' id=singleimagedata.id %}">
    

    不要错过将image_color 字段添加到您的html 输入。
    因为,在您的情况下,image_color 字段模型被设计为必填字段

    从目录中删除和更新旧图像文件;

    import os
    from django.conf import settings
    
    # your imported module...
    
    
    def updateimage(request, id):  #this function is called when update data
        old_image = ImageModel.objects.get(id=id)
        form = ImageForm(request.POST, request.FILES, instance=old_image)
    
        if form.is_valid():
    
            # deleting old uploaded image.
            image_path = old_image.image_document.path
            if os.path.exists(image_path):
                os.remove(image_path)
    
            # the `form.save` will also update your newest image & path.
            form.save()
            return redirect("/myapp/productlist")
        else:
            context = {'singleimagedata': old_image, 'form': form}
            return render(request, 'demo/editproduct.html', context)
    

    【讨论】:

    • 谢谢,它正在工作。
    【解决方案2】:

    我在更新用户的 profile_pic 时遇到了类似的问题。我用以下代码解决了这个问题,我认为这可能会有所帮助:

    模型.py

    class Profile(models.Model):
        # setting o2o field of user with User model
        user_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
        first_name = models.CharField(max_length=70, null=True, blank=True)
        last_name = models.CharField(max_length=70, null=True, blank=True)    
        profile_pic = models.ImageField(upload_to="images", blank=True, null=True,)
    
    
        def __str__(self):
            return str(self.user_name)
    

    forms.py

    class ProfileEditForm(ModelForm):
        class Meta:
            model = Profile
            fields = '__all__'
            # excluding user_name as it is a one_to_one relationship with User model
            exclude = ['user_name']
    

    views.py

    @login_required(login_url='login')
    def edit_profile(request, id):
        username = get_object_or_404(Profile, id=id)
        extended_pro_edit_form = ProfileEditForm(instance=username)
        if request.method == "POST":
            extended_pro_edit_form = ProfileEditForm(request.POST, request.FILES, instance=username)
            if extended_pro_edit_form.is_valid():
                extended_pro_edit_form.save()
                next_ = request.POST.get('next', '/')
                return HttpResponseRedirect(next_)
    
        context = {'extended_pro_edit_form': extended_pro_edit_form}
        return render(request, 'edit_profile.html', context)
    

    edit-profile.html

    <form action="" method="post"
                  enctype="multipart/form-data">
                {% csrf_token %}
                {{ extended_pro_edit_form.as_p }}
                {{ extended_pro_edit_form.errors }}
                <!--To redirect user to prvious page after post req-->
                <input type="hidden" name="next" value="{{ request.GET.next }}">
    
                <button type="submit">UPDATE</button>
    
            </form>
    

    【讨论】:

      【解决方案3】:

      @binpy 的回答应该可以解决您的问题。除了你的第二个答案,你可以这样做:

      def updateimage(request, id):  #this function is called when update data
          data = ImageModel.objects.get(id=id)
          form = ImageForm(request.POST,request.FILES,instance = data)
          if form.is_valid():
              data.image_document.delete()  # This will delete your old image
              form.save()
              return redirect("/myapp/productlist")
          else:
              return render(request, 'demo/editproduct.html', {'singleimagedata': data})
      

      检查 django 文档上的 delete() 方法。

      【讨论】:

      • 感谢您的帮助。我试过了,但它对我不起作用。其余所有数据正在更新。imageField 没有更新。
      • 它是从form.is_valid()传递过来的吗?
      • 是的。我们可以使用 Updateview 来做到这一点。但它也不起作用
      【解决方案4】:

      有时缓存的旧图像之类的东西不会在前端被替换,因此您可能只需要按CTRL + F5 强制刷新或清除您的浏览历史记录。

      @binpy 给出的答案是需要更新,以便将文件传递到后端。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-29
        • 2020-08-10
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2020-11-19
        • 2011-11-21
        • 2019-05-31
        相关资源
        最近更新 更多