0

I have a simple model:

class TestRentalObject(models.Model):
some_field = models.TextField()

build_year = models.PositiveSmallIntegerField(
    blank=True,
    null=True,
    validators=[MinValueValidator(1300), MaxValueValidator(2100)],
)

with ModelSerializer:

class TestRentObjectSerializer(serializers.ModelSerializer):
class Meta:
    model = TestRentalObject

    fields = (
        "some_field",
        "build_year"
    )

And here is input field from form:

<input type="number" class="input-group__input input-group__input_no-require is-invalid" id="field-rent.build_year" placeholder="" name="rent.build_year">

When I keep this field empty, serializer sees it as invalid.

In [8]: data = {'some_field': 'some_text', 'build_year': ''}
In [9]: rs = TestRentObjectSerializer(data=data)
In [10]: rs.is_valid()
Out[10]: False
In [11]: rs.errors
Out[11]: {'build_year': [ErrorDetail(string='A valid integer is required.', code='invalid')]}

I believe the problem is that I get build_year as an empty string and not None. But how to do it correctly?

Myroslav Hryshyn
  • 716
  • 7
  • 18
  • 1
    Try without "build_year" key, Like: `data = {'some_field': 'some_text'}` – Neeraj Kumar Jan 17 '19 at 10:45
  • @NeErAjKuMaR it works, but how to eliminate this field from the form if it's not filled? – Myroslav Hryshyn Jan 17 '19 at 10:49
  • It based on your frontend part, but you can also remove from Django with the condition if it's blank remove key from data dict. – Neeraj Kumar Jan 17 '19 at 10:52
  • @NeErAjKuMaR I see. Thanks, I thought there is a less patchy way to do it, cause it looks like a kind of popular scenario. – Myroslav Hryshyn Jan 17 '19 at 10:54
  • Does this answer your question? [Post empty date field error with Django rest framework](https://stackoverflow.com/questions/46871046/post-empty-date-field-error-with-django-rest-framework) – Spatz Apr 20 '22 at 11:24

1 Answers1

0

As NeErAj KuMaR recommended in comments I added a few lines into my view method.

    if request.data["rent"].get("build_year") == "":
        del request.data["rent"]["build_year"]

    serializer = TestRentObjectSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)

It looks a bit patchy, but I didn't find better way to do this.

Myroslav Hryshyn
  • 716
  • 7
  • 18