简体   繁体   中英

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?

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.

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM