akaphenom
akaphenom

Reputation: 6888

Django: DateField "This field cannot be blank."

I'm posting a rest request like this:

{title:some title, recurring:true, day:Wednesday, time:12:30, description:some text}

I am not passing the date because the event is recurring and the value should be empty. The server response is:

{"date": ["This field cannot be blank."]}

Here is the relevant python code:

class Event(models.Model):
    title = models.CharField(max_length=200)
    recurring = models.BooleanField()
    day = models.CharField(max_length=20, blank=True)
    date = models.DateField(null=True)
    time = models.TimeField()
    description = models.CharField(max_length=500)
    venue = models.CharField(max_length=200, blank=True)
    venueAddress = models.CharField(max_length=200, blank=True)
    venueCity = models.CharField(max_length=200, blank=True)

class EventSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Event

class EventViewSet(viewsets.ModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer

I am not completely sure where the message is coming back from. Is my model defined correctly? Do I need extra work in my serializer?

Upvotes: 13

Views: 17043

Answers (3)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Add the blank=True parameter to the definition of your date field if you want that field to be optional.

From the docs:

Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

Upvotes: 23

Andrew Gorcester
Andrew Gorcester

Reputation: 19953

The first step is to change your field description like so:

date = models.DateField(null=True, blank=True)

null=True is insufficient because that is only a directive relevant to table creation, not to validation. null and blank are separate concepts because there are situations where you only want one and not the other.

By the way, in almost all cases a date and a time field can be compressed into one DateTimeField.

Upvotes: 7

Jiaaro
Jiaaro

Reputation: 76888

It looks like you're using a library which in turn uses django.forms.ModelForm.

If this is the case, you can add blank=True to your DateField to resolve the issue.

class Event(models.Model):
    title = models.CharField(max_length=200)
    recurring = models.BooleanField()
    day = models.CharField(max_length=20, blank=True)
    date = models.DateField(null=True, blank=True)
    time = models.TimeField()
    description = models.CharField(max_length=500)
    venue = models.CharField(max_length=200, blank=True)
    venueAddress = models.CharField(max_length=200, blank=True)
    venueCity = models.CharField(max_length=200, blank=True)

Upvotes: 1

Related Questions