Django UpdateView does not validate form fields, and does not update

70 Views Asked by At

I have created the following Django UpdateView:

class ProfileSettingsView(SuccessMessageMixin, UpdateView):
    template_name = "accounts/settings/profile_settings.html"
    form_class = ProfileSettingsForm
    success_message = "Your profile has been successfully updated."
    success_url = reverse_lazy("accounts:profile_settings")
    context_object_name = "staff_member"

    def get_object(self, queryset=None):
        staff_member = get_object_or_404(StaffMember, user=self.request.user)
        return staff_member

The ProfileSettingsForm is defined as follows:

class ProfileSettingsForm(forms.ModelForm):
    class Meta:
        model = StaffMember
        fields = ["profile_image"]

And finally, the StaffMember model looks like this:

class StaffMember(models.Model):
    user = models.OneToOneField(
        "auth.User", on_delete=models.PROTECT, related_name="staff_member"
    )
    profile_image = models.ImageField(
        upload_to=get_profile_image_upload_path,
        blank=True,
        default="none.png",
        help_text="A profile image for this staff member. Must be square, and be in .png format.",
        validators=[FileExtensionValidator(["png"]), validate_img_square],
    )

My UpdateView renders correctly. I select an image from my local machine and press submit. The form posts successfully, and I see the success message. However, the validators, as defined on the StaffMember profile_image field have not been run. Also, the profile_image field is not updated.

Why is validation not being called on my form fields, and why are they not being updated? What am I missing?

1

There are 1 best solutions below

0
On BEST ANSWER

Have you checked that your form tag in the template contains the enctype="multipart/form-data" attribute? This is required to send the file uploads along. This is probably missing and then the file is "missing" from the form. Since the model and form field are not required, you don't get any validation on it, nor validation errors.

Relevant documentation: https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#basic-file-uploads

Note that request.FILES will only contain data if the request method was POST, at least one file field was actually posted, and the that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.