Django UpdateView doesn't allow empty field

Viewed 260

I have django 3 UpdateView class that is supposed to update Employee model. Employee has null=True field, however when I try to save model with this field empty, I got an error that this field should be filled before saving. How can I make UpdateView save null=True fields empty?

Here is UpdateView:

class EmployeeUpdate(LoginRequiredMixin, UpdateView):
    model = Employee
    success_url = "/"
    form_class = EmployeeUpdateForm
    template_name = "employee_update_form.html"
    login_url = "/login"

Here is EmployeeUpdateForm:

class EmployeeUpdateForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = (
            "first_name",
            "last_name",
            "email",
            "phone",
            "salary",
            "role",
        )

Here is Employee:

class Employee(models.Model):
    ATENDEE = "atendee"
    VIEWER = "viewer"
    ROLE_CHOICES = [
        (ATENDEE, "Atendee"),
        (VIEWER, "Viewer"),
    ]
    first_name = models.CharField(("FIRST NAME"), max_length=200, null=False)
    last_name = models.CharField(("LAST NAME"), max_length=200, null=False)
    email = models.EmailField(null=False)
    phone = models.CharField(max_length=20, null=True)
    salary = models.FloatField(default=0, null=False, validators=[validate_salary])
    role = models.CharField(("ROLE"), choices=ROLE_CHOICES, default=VIEWER, max_length=12)

Basically, I can't save empty phone field via template.

1 Answers

Employee has null=True field.

This is not sufficient, since null=True deals with what is done at the database side. If a field is not required (for forms, etc.), you work with blank=True [Django-doc]:

class Employee(models.Model):
    # …
    phone = models.CharField(max_length=20, null=True, blank=True)
    # …
Related