Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django throwing "Incorrect type. Expected URL string" on API call

I can't work out why Django REST framework is complaining it is expecting a string when it should be expecting an int! The error I am getting is:

{"_body":"{\"who_saw\":[\"Incorrect type. Expected URL string, received int.\"],\"item_seen\":[\"Incorrect type. Expected URL string, received int.\"]}","status":400,"statusText":"Ok","headers":{"Content-Type":["application/json;q=0.8"]},"type":2,"url":"http://127.0.0.1:8000/api/seen/"}

I am using the following Angular 2 http code to make a POST request from an app to a Django REST Framework server:

    let body = JSON.stringify({ item_seen: 1, who_saw: 2, liked: 0 });

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post('http://127.0.0.1:8000/api/seen/',
        body, {
          headers: headers
        })
        .map(res => res.json())
        .subscribe(
            data => {
              alert('DATA: '+JSON.stringify(data));
            },
            err => {
              alert('ERROR: '+JSON.stringify(err));
            },
            () => {
              alert('Complete');
            }
        );

My model is:

class Seen(models.Model):
    item_seen           = models.ForeignKey(Item, on_delete=models.CASCADE)     # id of the item that has been seen
    who_saw             = models.ForeignKey(User, on_delete=models.CASCADE)     # id of user who viewed it
    date_seen           = models.DateTimeField(auto_now_add=True)               # When item was viewed
    liked               = models.BooleanField(help_text='If the item was liked this is set to true')

My View is:

class SeenViewSet(viewsets.ModelViewSet):
    queryset = Seen.objects.all().order_by('-date_seen')
    serializer_class = SeenSerializer

    def perform_create(self, serializer):
        the_user = User.objects.get(pk=self.request.data['who_saw'])
        serializer.save(who_saw=the_user)

        the_item = Item.objects.get(pk=self.request.data['item_seen'])
        serializer.save(item_seen=the_item)

And my serializer is:

class SeenSerializer(serializers.HyperlinkedModelSerializer):
    username = serializers.SerializerMethodField()

    def get_username(self, obj):
        value = str(obj.who_saw)
        return value

    def get_keywords(self, obj):
        value = str(obj.keywords)
        return value

    class Meta:
        model = Seen
        fields = ('who_saw', 'item_seen', 'liked', 'date_seen', 'username')
like image 519
Bill Noble Avatar asked Apr 06 '16 15:04

Bill Noble


1 Answers

The problem is that you're using a serializers.HyperlinkedModelSerializer, you should use serializers.ModelSerializer or send the link of the ID you're sending as an int.

like image 194
wm3ndez Avatar answered Nov 14 '22 22:11

wm3ndez