[Django]-Django – "Incorrect type. Expected pk value, received str" error

28πŸ‘

βœ…

The issue is that you are passing the name of the related Destination object into the serializer, instead of passing the pk/id of the Destination object. So Django REST framework is seeing this and complaining, because it can’t resolve LA into an object.

It sounds like you may actually be looking for a SlugRelatedField, which allows you to identify objects by a slug (LA in this case) instead of their primary keys.

2πŸ‘

There is a minor difference between Django and Django Rest Framework whenever we try to add the Foreign key references to an instance

Let us assume we want to add the user references to another DB Table

Django

In Django, we reference the whole instance of the user as mentioned below

user = request.user

Django Rest Framework

However in DRF if we follow the same procedure we get the errors like

Incorrect type. Expected pk value, received str/User type

In order to overcome this error, we need to reference the Primary Key of the table instead (Here id is the PK)

user = request.user.id
πŸ‘€M A Rahul

1πŸ‘

Angular/Django Rest Framework

I had similar problem when trying to post a formdata that has a field with some array values. It turned out that I was using a wrong content-type in the post headers of angular frontend. All I needed was comment out Content-Type.

  Post(endpoint, postData) {
    let auth = `Bearer ${this.token}`;
    let headers = new HttpHeaders({
      // "Content-Type": "application/x-www-form-urlencoded",
      Authorization: auth
    });
    let fullurl = `${this.baseUrl}${endpoint}`;
   .....
  ....
}
πŸ‘€7guyo

Leave a comment