[Answered ]-Django rest api not accepting raw data

1πŸ‘

If you are using Django auth User model, then relationship between User and Groups is many to many. A user can belongs to more than one groups. So you should write a custom create method for your serializer if you want to work it for you with same payload. It will be something like this

from django.contrib.auth.models import Group
def create(self, validated_data):
     user = get_user_model().objects.create(
               email=validated_data.get('email'),
               first_name=validated_data.get('first_name'),
               last_name=validated_data.get('last_name')
            )
     user.set_password('password')
     g = Group.objects.get(id=validated_data.get('group')) 
     g.user_set.add(user)

You should set content type as json in postman.

1πŸ‘

You only need to post the data maybe like this,

{
    "password":"12345678",
    "email":"mymail@yopmail.com",
    "groups":[1],
    "first_name":"Arun",
    "last_name":"Joshi"
}

Couple things to keep in mind,

  • Relation between User and Groups is ManyToMany. So, the serializer accepts the data as a list only. Either you may need to write a custom create method, like @M Hassan suggested, or you just need to post it as a list.

  • Primary keys are integer fields, don’t post them as strings. If you do, make sure you write appropriate code for catching the same.

πŸ‘€zaidfazil

0πŸ‘

If you are using requests
set at your headers
content-type: application/json
Like this

headers= {'content-type':'application/json'}
data = {
"password":"12345678",
"email":"mymail@yopmail.com",
"groups":"1",
"first_name":"Arun",
"last_name":"Joshi"}
resp = requests.post(url, headers=headers, data=data)

For postman, just add headers like this
enter image description here

Check your project settings also:

REST_FRAMEWORK = {
'PAGE_SIZE': 10,
'DEFAULT_RENDERER_CLASSES': (
    'rest_framework.renderers.JSONRenderer',
    'rest_framework.renderers.BrowsableAPIRenderer',
)}

Check this also:

from rest_framework.parsers import JSONParser

class MyUserViewSet(viewsets.ModelViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer 
    parser_classes = (JSONParser,)
πŸ‘€A.Raouf

Leave a comment