简体   繁体   中英

Django rest framework post request not retrieving anything

I am trying to create a user creation api and post create api, the 'Get' request works fine but the post request is always empty. If there is anything I missed or need to add to the views, because the get request works fine for the post app. What could be the possible errors that are occuring.

Serializer.py


from rest_framework import serializers
from .models import User


class RegisterSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(
        style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = User
        fields = ['username', 'email',
                  'date_of_birth', 'password', 'password2']
        extra_kwargs = {'password': {'write_only': True}}

    def save(self):
        print("saved")
        user = User(email=self.validated_data['email'],
                    username=self.validated_data['username'],
                    date_of_birth=self.validated_data['date_of_birth']
                    )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError(
                {'password': 'Passwords must match.'})
        user.set_password(password)
        user.save()
        return user

Below is the views.py

from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import User
from .serializers import RegisterSerializer
from rest_framework.authtoken.models import Token
from rest_framework.parsers import JSONParser


@api_view(['POST', ])
def registration_view(request):
    if request.method == 'POST':
        serializer = RegisterSerializer(data=request.data)

        data = {}
        if serializer.is_valid():
            print("Hello")
            user = serializer.save()
            data['response'] = 'Successfuly registered a new User'
            data['date_of_birth'] = user.date_of_birth
            data['username'] = user.username
            data['email'] = user.email
            token = Token.objects.get(user=user)
            data['token'] = token
            return Response(data)
        else:
            return Response(serializer.errors)

No matter the post request I always get an error saying this field is required,

Here is the error -- screenshot

Can anybody help me please, Thank you

According to your screenshot you are sending data as query params with POST request. In Postman you should use body section with, for example, form-data option.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM