I’m having issue with implementing a PATCH request with drf. The model contains the following fields: id, message, budget, sender, receiver and status. When a post request is made for the first time, the only data being send is message, budget and receiver. Sender is being set as the current user while the receiver is also being set as a user with id sent in the request. The status field by default is set as PENDING. Now i want to create a PATCH endpoint from where i can update the status field to either REJECTED or ACCEPTED. However, i want the current user to be the receiver user. I have implemented all that, but now I’m getting error. Any help would be appreciated.
models file:
from django.utils import timezone
from django.db import models
from core.mixins import PrimaryKeyMixin
from user.models import User
from vehicle.models import Vehicle
STATUS_CHOICES = (("ACCEPTED", "ACCEPTED"),
("REJECTED", "REJECTED"), ("PENDING", "PENDING"))
class MakeOffer(PrimaryKeyMixin):
message = models.TextField(max_length=255)
created_at = models.DateTimeField(default=timezone.now)
budget = models.FloatField(null=True, blank=True)
sender = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='Sender')
reciever = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='Reciever')
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
status = models.CharField(
choices=STATUS_CHOICES, default="PENDING", max_length=10)
is_seen = models.BooleanField(default=False)
class Meta:
ordering = ["created_at"]
def __str__(self):
return self.message
views file:
from functools import partial
from django.shortcuts import render
from typing import List
from urllib import response
from django.db import transaction, DatabaseError
from django.shortcuts import render
from django.utils.translation import gettext as _
from rest_framework.generics import CreateAPIView, ListAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework import status
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from .serializers import MakeOfferSerializer, CreateMakeOfferSerializer, MakeOfferRecieverSerializer, UpdateMakeOfferSerializer, CreateUpdateMakeOfferSerializer
from .models import MakeOffer
# Create your views here.
class MakeOfferAPIView(CreateAPIView):
"""Add a vehicle Request"""
permission_classes = [IsAuthenticated]
queryset = MakeOffer.objects.all()
serializer_class = CreateMakeOfferSerializer
def post(self, request, *args, **kwargs):
print('test')
try:
with transaction.atomic():
data = self.request.data.copy()
serializer_vehicle_request = CreateMakeOfferSerializer(
data=data, context={"request": request})
if serializer_vehicle_request.is_valid(raise_exception=True):
serializer_vehicle_request.save()
response = serializer_vehicle_request.data
return Response(response)
except DatabaseError as e:
return Response(data=str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class MakeOfferListAPIView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = MakeOfferSerializer
def get_queryset(self):
print("User while fetching the vehicle requests: ", self.request.user)
return self.serializer_class.Meta.model.objects.filter(sender=self.request.user)
class MakeOfferRecieverListAPIView(ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = MakeOfferRecieverSerializer
def get_queryset(self):
print("User while fetching the vehicle requests: ", self.request.user)
return self.serializer_class.Meta.model.objects.filter(reciever=self.request.user)
class MakeOfferRecieverUpdateAPIView(UpdateAPIView):
queryset = MakeOffer.objects.all()
permission_classes = [IsAuthenticated]
serializer_class = UpdateMakeOfferSerializer
def patch(self, request, *args, **kwargs):
try:
pk = kwargs.get('pk')
offer = MakeOffer.objects.get(id=pk)
print(offer.reciever)
print(self.request.user)
serializer = CreateUpdateMakeOfferSerializer(
data=offer, many=False, partial=True)
if serializer.is_valid(raise_exception=True):
offer = serializer.save()
return Response(UpdateMakeOfferSerializer(offer).data)
except Exception as e:
return Response(data=str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
serializer file:
from dataclasses import field
from xml.etree.ElementInclude import include
from rest_framework import serializers
from user.models import User
from user.serializers import UserSerializer
from vehicle.models import Vehicle
from vehicle.serializers import VehicleSerializer
from ..models import MakeOffer
class CreateMakeOfferSerializer(serializers.ModelSerializer):
sender = UserSerializer(
default=serializers.CurrentUserDefault())
reciever = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all())
vehicle = serializers.PrimaryKeyRelatedField(
queryset=Vehicle.objects.all())
class Meta:
depth = 1
model = MakeOffer
exclude = ['created_at', 'status', 'is_seen']
class MakeOfferSerializer(serializers.ModelSerializer):
sender = UserSerializer(default=serializers.CurrentUserDefault())
reciever = UserSerializer()
vehicle = VehicleSerializer()
class Meta:
depth = 1
model = MakeOffer
exclude = ['is_seen']
class MakeOfferRecieverSerializer(serializers.ModelSerializer):
sender = UserSerializer()
reciever = UserSerializer(default=serializers.CurrentUserDefault())
vehicle = VehicleSerializer()
class Meta:
depth = 1
model = MakeOffer
fields = '__all__'
class UpdateMakeOfferSerializer(serializers.ModelSerializer):
class Meta:
model = MakeOffer
fields = ['status']
class CreateUpdateMakeOfferSerializer(serializers.ModelSerializer):
reciever = serializers.PrimaryKeyRelatedField(
read_only=True)
sender = serializers.PrimaryKeyRelatedField(read_only=True)
vehicle = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = MakeOffer
fields = ['status']