Home > Blockchain >  How to make some fields optional in Django ORM
How to make some fields optional in Django ORM

Time:02-12

I've coded a function that signs up a user. In my sterilizer the name field is optional but whenever I try to create a user without giving a name, I just face KeyError: 'name'. what should I do to make this code work?

def post(self, request):
        if request.user.is_anonymous:
            data = RegisterationSerializer(data=request.data)
            if data.is_valid():
                User.objects.create_user(email=data.validated_data['email'], username=data.validated_data['username'],
                 password=data.validated_data['password'], name=data.validated_data['name'])    
                return Response({
                "message": f'{data.validated_data["email"]} account was created successfully'
                }, status=status.HTTP_201_CREATED)
            
            else:
                return Response(data.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({
                "message": "You already authorized"
            }, status=status.HTTP_400_BAD_REQUEST)

CodePudding user response:

The problem is you are trying to access to name in your validated_data. But there is no name.

you can do something like User.objects.create_user(**data.validated_data) or you can do

User.objects.create_user(
        email=data.validated_data['email'], 
        username=data.validated_data['username'],
        password=data.validated_data['password'], 
        name=data.validated_data['name'] if 'name' in data.validated_data else '') # or None  
  • Related