Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: DateField "This field cannot be blank."

Tags:

python

django

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?

like image 825
akaphenom Avatar asked Aug 20 '13 15:08

akaphenom


2 Answers

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.

like image 111
Peter DeGlopper Avatar answered Oct 14 '22 09:10

Peter DeGlopper


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.

like image 24
Andrew Gorcester Avatar answered Oct 14 '22 08:10

Andrew Gorcester