Home > other >  UpdateView is not removing image when updating form - Django
UpdateView is not removing image when updating form - Django

Time:03-10

I have a form that the user can upload the pictures into the post, this is working fine, but the problem is when the user wants to remove that current picture that the post has. It can be updated to another picture, but it can't be removed from the post to be "Blank".

Models.py

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    form_class = PostEditForm
    model = Post

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

forms.py

class PostEditForm(forms.ModelForm):
    thumb = forms.ImageField(required=False, widget=forms.FileInput)

    class Meta:
        fields = ['title', 'content', 'thumb', 'date_start', 'start_time',
              'date_end', 'end_time', ]
        model = Post

CodePudding user response:

By default for an image field with an uploaded file you should be getting text as "Currently" which would indicate the current image and a checkbox labeled "Clear" which would allow you to unset the field.

The reason you don't have these options is because you have explicitly set the fields widget to FileInput. You should instead be using ClearableFileInput [Django docs] (or simply skip the widget argument since this is the default) which gives you those options:

class PostEditForm(forms.ModelForm):
    thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput)

    class Meta:
        fields = ['title', 'content', 'thumb', 'date_start', 'start_time',
              'date_end', 'end_time', ]
        model = Post
  • Related