Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

How do I pass 'user_id' to CustomerSerializer?


I don't know how to pass user_id from requests.user.id and use it in the CustomerSerializer to save the object to the database. The error stems from the fact that user_id exists in the customer table in the database but it does not show up as a field to be passed in the rest_framework API frontend (only phone and profile_image do).

Here is the Customer model:

class Customer(models.Model):
    phone = models.CharField(max_length=14)
    profile_image = models.ImageField(blank=True, null=True)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Here is the ViewSet:

class CustomerViewSet(ModelViewSet):
    queryset = Customer.objects.all()
    permission_classes = [permissions.IsAdminUser]
    serializer_class = CustomerSerializer

    # Only admin users can make requests other than 'GET'
    def get_permissions(self):
        if self.request.method == 'GET':
            return [permissions.AllowAny()]
        return [permissions.IsAdminUser()]

    @action(detail=False, methods=['GET', 'PUT'])
    def me(self, request):
        customer, created = Customer.objects.get_or_create(user_id=request.user.id)
        if request.method == 'GET':
            serializer = CustomerSerializer(customer)
            return Response(serializer.data)
        elif request.method == 'PUT':
            serializer = CustomerSerializer(customer, data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data)

... and here is the Serializer:

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ['id', 'user_id', 'profile_image', 'phone']
```python


... and when I try to save a new customer by sending a POST request to the endpoint with the following data:

```json
{
    "profile_image": "Images/image.png",
    "phone": "009293930"
}

I get the following error:

IntegrityError at /api/customers/
(1048, "Column 'user_id' cannot be null")
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/customers/
Django Version: 4.0.6
Exception Type: IntegrityError
Exception Value:    
(1048, "Column 'user_id' cannot be null")
Exception Location: /home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/lib/python3.8/site-packages/pymysql/err.py, line 143, in raise_mysql_exception
Python Executable:  /home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/bin/python
Python Version: 3.8.10
Python Path:    
['/home/caleb/Desktop/Cribr',
 '/home/caleb/Desktop/Cribr',
 '/snap/pycharm-professional/290/plugins/python/helpers/pycharm_display',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/caleb/.local/share/virtualenvs/Cribr-svgsjjVF/lib/python3.8/site-packages',
 '/snap/pycharm-professional/290/plugins/python/helpers/pycharm_matplotlib_backend']
Server time:    Thu, 28 Jul 2022 23:38:53 +0000

I figured the issue here is that the serializer class is not getting the user_id value from the POST request. I tried passing request.user.id to the serializer from the viewset through a context object (i.e., context={'user_id': request.user.id}) but I couldn't figure out how to then add it to the validated data which the serializer passes to the save method.

Any help on this issue will be much appreciated. Thanks in advance.


Solution

  • Okay, I managed to solve it by overriding the create method in the serializer. I added the following:

    class CustomerSerializer(serializers.ModelSerializer):
        class Meta:
            model = Customer
            fields = ['id', 'user_id', 'profile_image', 'phone']
            read_only_fields = ['user_id']
    
        
        # NEW ---------------------------------
            def create(self, validated_data):
                user = self.context['request'].user
                customer = Customer.objects.filter(user_id=user)
                if customer.exists():
                    raise serializers.ValidationError(
                    'Customer already exists')
                else:
                    customer = Customer.objects.create(
                        user=user, **validated_data)
                return customer
    

    The object saves fine now.