“applicant”: [ “This field may not be null.”]

serializers.py

from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from .models import FieldUser, BaseApplicant, Applicant, CoApplicant, Guarantor


class VerificationMobileSerializer(serializers.Serializer):
    mobile_number = serializers.CharField(max_length=15)


class FieldUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = FieldUser
        fields = ['id', 'username', 'first_name', 'last_name', 'email', 'mobile_number',
                  'profile_photo', 'address', 'pin_code', 'city', 'state']

    profile_photo = serializers.ImageField(
        required=False)

    def update(self, instance, validated_data):
        validated_data.pop('profile_photo', None)

        instance.username = validated_data.get('username', instance.username)
        instance.first_name = validated_data.get(
            'first_name', instance.first_name)
        instance.last_name = validated_data.get(
            'last_name', instance.last_name)
        instance.email = validated_data.get('email', instance.email)
        instance.mobile_number = validated_data.get(
            'mobile_number', instance.mobile_number)
        instance.address = validated_data.get('address', instance.address)
        instance.pin_code = validated_data.get('pin_code', instance.pin_code)
        instance.city = validated_data.get('city', instance.city)
        instance.state = validated_data.get('state', instance.state)

        instance.save()
        return instance


class ApplicantSerializer(serializers.ModelSerializer):
    class Meta:
        model = Applicant
        fields = '__all__'


class CoApplicantSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoApplicant
        fields = '__all__'


class GuarantorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Guarantor
        fields = '__all__'


class ApplicantSubmissionSerializer(serializers.Serializer):
    applicant = ApplicantSerializer()
    coApplicants = CoApplicantSerializer(many=True)
    granters = GuarantorSerializer(many=True)

    def to_internal_value(self, data):
        # Extract applicant data
        applicant_data = data.pop('applicant')

        # Extract applicant ID
        applicant_id = None
        if 'id' in applicant_data:
            applicant_id = applicant_data['id']

        # Prepare co-applicants data with the applicant field populated with ID
        co_applicants_data = []
        for co_applicant_data in data.get('coApplicants', []):
            co_applicant_data['applicant'] = applicant_id
            co_applicants_data.append(co_applicant_data)

        # Prepare guarantors data with the applicant field populated with ID
        granters_data = []
        for granter_data in data.get('granters', []):
            granter_data['applicant'] = applicant_id
            granters_data.append(granter_data)

        # Combine the modified data
        modified_data = {
            'applicant': applicant_data,
            'coApplicants': co_applicants_data,
            'granters': granters_data
        }

        return super().to_internal_value(modified_data)

    def create(self, validated_data):
        # Create the main applicant instance
        applicant_instance = Applicant.objects.create(
            **validated_data['applicant'])

        # Create co-applicant instances linked to the main applicant
        for co_applicant_data in validated_data.get('coApplicants', []):
            CoApplicant.objects.create(
                applicant=applicant_instance, **co_applicant_data)

        # Create guarantor instances linked to the main applicant
        for granter_data in validated_data.get('granters', []):
            Guarantor.objects.create(
                applicant=applicant_instance, **granter_data)

        return applicant_instance

views.py
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import VerificationMobileSerializer, FieldUserSerializer, ApplicantSubmissionSerializer
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404
from .models import FieldUser
from rest_framework import generics

@method_decorator(csrf_exempt, name='dispatch')
class VerifyMobileAPIView(APIView):
    def post(self, request):
        serializer = VerificationMobileSerializer(data=request.data)
        if serializer.is_valid():
            mobilenumber = serializer.validated_data['mobile_number']
            queryset = FieldUser.objects.filter(mobile_number=mobilenumber)
            if queryset.exists():
                user_serializer = FieldUserSerializer(queryset, many=True)
                return Response({
                    'detail': 'Verification successful. Login successful.',
                    'users': user_serializer.data
                }, status=status.HTTP_200_OK)
            return Response({'detail': 'Invalid mobile number'}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class GetUserProfileAPIView(APIView):
    def get(self, request, pk=None):
        if pk is not None:
            user = get_object_or_404(FieldUser, pk=pk)
            serializer = FieldUserSerializer(user)
            return Response(serializer.data)
        else:
            user = request.user
            serializer = FieldUserSerializer(user)
            return Response(serializer.data)


@method_decorator(csrf_exempt, name='dispatch')
class UserProfileUpdateAPIView(generics.UpdateAPIView):
    queryset = FieldUser.objects.all()
    serializer_class = FieldUserSerializer


@method_decorator(csrf_exempt, name='dispatch')
class ApplicantSubmissionView(APIView):
    def post(self, request):
        serializer = ApplicantSubmissionSerializer(data=request.data)
        print('hello1')
        if serializer.is_valid():
            print('hello2')
            # Save the validated data
            serializer.save()

            # Return a success response
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        # If the data is not valid, return the errors
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

when i am try

http://127.0.0.1:8000/api/submit-applicant/

with below json

{
    "applicant": {
        "name": "John Doe",
        "contact_no": "1234567890",
        "aadhar_no": "1234 5678 9012",
        "pan_no": "ABCDE1234F",
        "present_address": "123 Main Street, City",
        "permanent_address": "456 Elm Street, City",
        "residence_status": "Owned",
        "ownership_proof_type": "E-Bill/Water Tax",
        "duration_to_stay": "5 years",
        "landmark": "Near the park",
        "area_of_house": "1500 sq. ft.",
        "color_of_house": "Beige",
        "no_of_persons_living_in_home": 4,
        "no_of_earning_members": 2,
        "neighbor_name": "Smith Family",
        "met_person_at_home": "Yes",
        "office_business_name": "ABC Enterprises",
        "office_business_address": "789 Business Avenue, City",
        "duration_of_service_business": "10 years",
        "designation_of_applicant": "Manager",
        "gstin_or_id_card": "GST1234567",
        "nature_of_business": "Retail",
        "staff_name_and_designation": "John Smith, Sales Executive",
        "no_of_employees": 10,
        "contact_no_of_business": 9812345678,
        "landmark_of_business": "Near the mall",
        "ownership_proof_type_of_business": "E-Bill/Water Tax"
        
    },
    "coApplicants": [
        {
            "name": "Jane Doe",
            "contact_no": "9876543210",
            "aadhar_no": "5678 9012 3456",
            "pan_no": "FGHIJ5678K",
            "present_address": "789 Oak Street, City",
            "permanent_address": "901 Pine Street, City",
            "residence_status": "Rented",
            "ownership_proof_type": "E-Bill/Water Tax",
            "duration_to_stay": "3 years",
            "landmark": "Near the school",
            "area_of_house": "1200 sq. ft.",
            "color_of_house": "Blue",
            "no_of_persons_living_in_home": 3,
            "no_of_earning_members": 1,
            "neighbor_name": "Johnson Family",
            "met_person_at_home": "No"
            
        }
    ],
    "granters": [
        {
            "name": "James Smith",
            "contact_no": "2345678901",
            "aadhar_no": "9012 3456 7890",
            "pan_no": "KLMNO6789P",
            "present_address": "345 Maple Street, City",
            "permanent_address": "567 Cedar Street, City",
            "residence_status": "Owned",
            "ownership_proof_type": "E-Bill/Water Tax",
            "duration_to_stay": "7 years",
            "landmark": "Near the hospital",
            "area_of_house": "1800 sq. ft.",
            "color_of_house": "White",
            "no_of_persons_living_in_home": 5,
            "no_of_earning_members": 2,
            "neighbor_name": "Doe Family",
            "met_person_at_home": "Yes"
        }
    ]
}
getting the error

{
    "coApplicants": [
        {
            "applicant": [
                "This field may not be null."
            ]
        }
    ]
} 

and my applicant is not creating so id is null

soltion for the above error

New contributor

Sandeep Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật