Home > Net >  Django Rest Framework Postman 'POST' request error
Django Rest Framework Postman 'POST' request error

Time:03-11

I'm still having this error when trying to do a post request from postman.

{
    "username": [
        "This field is required."
    ],
    "password": [
        "This field is required."
    ]
}

I can make the same post request successfully from my DRF localhost, but when i try on postman i get the error above.

How can I solve it?

Views.py


class PlayThingList(viewsets.ModelViewSet):
    serializer_class = PlayThingSerializer
    queryset = PlayThing.objects.all()

class UserViewset(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

Serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User 
        fields = ['id', 'username', 'password']

        extra_kwargs = {'password': {
            'write_only':True,
            'required':True
        }}

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user)
        return user

urls.py

router = DefaultRouter()
router.register('playthings', PlayThingList, basename='playthings')
router.register('users', UserViewset)




urlpatterns = [
    path('playmates/', include(router.urls)),
]

Project urls.py


from django.contrib import admin
from django.urls import path, include
from rest_framework.authtoken.views import obtain_auth_token
app_name = 'playthings'

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include('playthings.urls')),
    path('auth/', obtain_auth_token)
]

UPDATE

I made some changes based on the error messages and guides in the comments and I can now create users.

Problem is, after sending the user credentials in the form, i get this error in postman.

enter image description here

CodePudding user response:

Try adding the following in your POSTMAN

Headers section:

KEY Value
Accept application/json

Body section (choose raw or x-www-form-urlencoded):

KEY Value
username (your username)
password (your password)

CodePudding user response:

In your userviewset, you are using UserSerializer. This way you can not create users. To create a user you will have to extend registeruser functionality.

Check out the code from rest-framework and use the same logic in your create method of userviewset. if you want to register a user.

Registeruser is all together a different thing.

Rest framework by default has a url to register users, use that url, it will handle everything for you.

CodePudding user response:

Problem Solved!

The issue was with the token create() method. I changed

create(user) to create(user=user)

ref: serializers.py

def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user)
        return user

Thank you to everyone that helped!

  • Related