DRF Invalid value Error

200 views
Skip to first unread message

Amed Sheriff

unread,
Mar 29, 2023, 7:06:08 PM3/29/23
to django-res...@googlegroups.com
Hello Team,

Please i need help with this which has taken me over two weeks and still couldn't come up with anything after surfing the internet. 

Is there any posibility to post data to foreign key using the value rather than the FK ID. Bcz i have tried all kinds of scenarios but none seemed to work with this even though they do refer to  "SlugRelatedField" usage.

This is my model.

class Counter(models.Model):
    userid = models.ForeignKey(Identification,related_name="userName",       verbose_name=_("User ID"), on_delete=models.CASCADE, null=True)
    counter = models.IntegerField(_("Counter"), blank=True, null=True)
    date_and_time = models.DateTimeField(_("Date and Time"), default=timezone.now)

    def __str__(self):
        return str(self.counter)

This is my serializer.

class Message_Counter_Serializer(serializers.ModelSerializer):
    userid = serializers.SlugRelatedField(
        slug_field='userName',
        queryset=Identification.objects.all()
    )
   
    class Meta:
        model = Counter
        fields = '__all__'

Post:
{
"counter": "2",
"userid": "ya"
}

Error:
 {"userid":["Invalid value."]}

Thanks in advance

Best regards

Amed.


Tanveer Ahmad

unread,
Mar 29, 2023, 8:16:05 PM3/29/23
to django-res...@googlegroups.com
I think so, there's no way you have to send id only that must be unique 

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/CADteO3_BuN97kaGyiHU-b5VETJHLyxB4tD-ePn_FTuKEZsyKQg%40mail.gmail.com.

Abhishek Chauhan

unread,
Mar 29, 2023, 11:13:01 PM3/29/23
to django-res...@googlegroups.com
Show the views.py 

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/CADteO3_BuN97kaGyiHU-b5VETJHLyxB4tD-ePn_FTuKEZsyKQg%40mail.gmail.com.
--
Abhishek Chauhan

✆ : 9560 432 275





Umair Ramzan

unread,
Mar 30, 2023, 1:02:24 AM3/30/23
to django-res...@googlegroups.com
You can overrite the to_internal_value method in the serializer.

Field - candidate key 
---
def to_internal_value(self, data):
    userid = Identification.obejcts.get(field=data["userid"]).id

   resource = data.copy().update({'userid':userid})
   return super().to_internal_value(resource)
   

  


Amed Sheriff

unread,
Mar 30, 2023, 7:41:55 AM3/30/23
to django-res...@googlegroups.com
Hello Team 

Please this is the view requested.

class Counter_Viewsets(errorhandler, viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasResourceScope]
    serializer_class = Message_Counter_Serializer

    def get_queryset(self):
        return Counter.objects.all().filter(userid__user_name=self.request.user)

Thanks and very much appreciated your support 

Best regards


Amed.


Abhishek Chauhan

unread,
Mar 30, 2023, 8:01:40 AM3/30/23
to django-res...@googlegroups.com
haven’t tried your code but can you like override 

lookup_field = “userid” in the viewset class in views.py so that way your view will look for the userid while making the post request .

But somehow after the lookup is done then the view will try to save to the model using the serializers so there I am not very sure if it will work as the field , userid, defined in your serializer Message_Counter_Serializer .Try the lookup_field  first 

Amed Sheriff

unread,
Mar 30, 2023, 8:37:21 AM3/30/23
to django-res...@googlegroups.com
Hello @Umair Ramzan,

Please with your approach i am getting this error.
Code: 

  userid = serializers.SlugRelatedField(
        slug_field='userName',
        queryset=Identification.objects.all()
    )
   
    class Meta:
        model = Counter
        fields = '__all__'

    def to_internal_value(self, data):
        userid = Identification.obejcts.get(field=data["userid"]).id
        resource = data.copy().update({'userid':userid})
        return super().to_internal_value(resource)

Error:

raise FieldError(
django.core.exceptions.FieldError: Cannot resolve keyword 'field' into field. Choices are: ...

Amed Sheriff

unread,
Mar 30, 2023, 9:57:32 AM3/30/23
to django-res...@googlegroups.com
I believe the lookup_field works with get not post, however i did tried it and got this error for POST
lookup_field='userid'
Error:

{"userid":["Incorrect type. Expected pk value, received str."]}

Please is there anyone that understands how to work around this.  

Umair Ramzan

unread,
Mar 30, 2023, 10:13:32 AM3/30/23
to django-res...@googlegroups.com
You have to replace the field with relevant model field name in your identification Model.


Amed Sheriff

unread,
Apr 5, 2023, 7:09:04 PM4/5/23
to django-res...@googlegroups.com
Hello Team,

I am just following up on the above discussion as it's been days now and I haven't heard from anyone.

On Thu, Mar 30, 2023 at 4:48 PM Amed Sheriff <ameds...@gmail.com> wrote:
Hello Team,

Please could look into it for me maybe i am doing something wrong.


This is my model.

class Counter(models.Model):
    userid = models.ForeignKey(Identification,related_name="userName",       verbose_name=_("User ID"), on_delete=models.CASCADE, null=True)
    counter = models.IntegerField(_("Counter"), blank=True, null=True)
    date_and_time = models.DateTimeField(_("Date and Time"), default=timezone.now)

    def __str__(self):
        return str(self.counter)

This is my serializer.

class Message_Counter_Serializer(serializers.ModelSerializer):
    userid = serializers.SlugRelatedField(
        slug_field='userName',
        queryset=Identification.objects.all()
    )
   
    class Meta:
        model = Counter
        fields = '__all__'

This is my  View

class Counter_Viewsets(errorhandler, viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasResourceScope]
    serializer_class = Message_Counter_Serializer

    def get_queryset(self):
        return Counter.objects.all().filter(userid__user_name=self.request.user)

This is my  Post:
{
"counter": "2",
"userid": "yasmin"
}

Thanks in advance.

On Thu, Mar 30, 2023 at 5:02 AM Umair Ramzan <umairper...@gmail.com> wrote:

Amed Sheriff

unread,
Apr 5, 2023, 8:03:50 PM4/5/23
to django-res...@googlegroups.com
Guys just found a solution.
Thanks to those that did contribute, I did appreciate it.

On Fri, Mar 31, 2023 at 1:24 PM Amed Sheriff <ameds...@gmail.com> wrote:
Hello Tanveer Ahmad,

We are not sending the ID rather the FK value associated with which userid (a name which already unique)

Thanks by the way. 

Reply all
Reply to author
Forward
0 new messages