Clearing ImageField in Django

Asked by At

My project has users which have a profile and can edit their profile, one of which is their profile picture. All the user information can be edited or cleared with no problem, except the profile picture. I can edit it, but I cannot clear it.


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=64,blank=True)
    profilePic = models.ImageField(blank=True, null=True, upload_to= path_and_rename)
    phoneNumber = models.CharField(max_length=12,blank=True)
    streetAddress = models.CharField(max_length=64,blank=True)

My for editing the profile. I also crop the picture based on the user inputs.

class EditProfile(forms.ModelForm):  
    class Meta:
        model = Profile
        fields = ("name", "phoneNumber","streetAddress")
        labels = {
        'phoneNumber': _('Phone Number'),   
        'streetAddress': _('Street Address and/or Postal Code'),

class PhotoForm(forms.ModelForm):
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        model = Profile
        fields = ('profilePic', 'x', 'y', 'width', 'height', )

    def save(self):
        photo = super(PhotoForm, self).save()

        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        image =
        cropped_image = image.crop((x, y, w+x, h+y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)

        return photo

Finally, my

def settings(request):
    user= request.user 
    profile = Profile.objects.get(user=user)
    if request.method == 'GET':
        profile_form = EditProfile(instance=profile)
        f1= UserProfile(user=request.user)
        photo = PhotoForm(instance= profile)
        return render(request, 'listings/settings.html', {'form': f1,'form2': profile_form, 'profilePic':photo})

    elif request.method == 'POST':
        profile_form = EditProfile(request.POST, request.FILES, instance=profile)
        photo_form = PhotoForm(request.POST, request.FILES,instance=profile)
        if photo_form.is_valid():

        messages.success(request, 'Your profile has been updated!')
        return redirect("/settings")

In my template, I click on clear image button, I even set id_profilePic to "", yet the image remains in the object.

1 Answers

Ibrahim Fakih On

I fixed it. The problem was whenever I try to clear, the x,y,width and height have no values. So it never enters the if statement in

 if photo_form.is_valid():

I fixed it by giving initial values to them