Anoop
Anoop

Reputation: 543

AssertionError: Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information

I am facing some issues while creating an API

Here is my model

class Education(AuditFields):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    school = models.CharField(max_length=255, blank=True)
    field_of_study = models.CharField(max_length=255, blank=True)
    start_year = models.DateField(default=datetime.now)
    end_year = models.DateField(default=datetime.now)

This is my serializer :

class EducationSerializer(ModelSerializer):
    class Meta:
        model = Education
        fields = '__all__'

views :

class EducationCreateView(CreateAPIView):
    def get_queryset(self, *args, **kwargs):
        queryset_list = Education.objects.filter(
            user=self.request.user)

        return queryset_list
    serializer_class = EducationSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

If I am post something it shows the following message

{
    "user": [
        "This field is required."
    ]
}

if I change my serializer like this

class EducationSerializer(ModelSerializer):
    class Meta:
        model = Education
        fields = '__all__'
        extra_kwargs = {'user': {'required': False}}

I am getting an error like this

Expected a date, but got a datetime. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly.

How to resolve this .

Upvotes: 5

Views: 12031

Answers (2)

Tarique
Tarique

Reputation: 1461

The error is because of the two fields in model: start_year and end_year

You have defined them to be of date type but assigning a datetime value as default.

Try to modify the two fields in model as given and also import datetime:

import datetime

    start_year = models.DateField(default=datetime.date.today)
    end_year = models.DateField(default=datetime.date.today)

Hope this helps

Upvotes: 9

Charnel
Charnel

Reputation: 4432

You can try to explicitly define fields for serializer:

class EducationSerializer(ModelSerializer):

    start_year = serializers.DateTimeField(format="%Y-%m-%d")
    end_year = serializers.DateTimeField(format="%Y-%m-%d")
    ...

Upvotes: 9

Related Questions