Home > Enterprise >  Django: returning empty {} with 400 Bad request for post method
Django: returning empty {} with 400 Bad request for post method

Time:09-18

I am trying to implement an attendance system as part of a bigger project that handles multiple schools at the same time but the endpoint is returning an empty {} with a 400_BAD_REQUEST

Attendance/models.py

class Attendance(models.Model):
Choices = (
    ("P", "Present"),
    ("A", "Absent"),
    ("L", "On leave"),
)

user = models.ForeignKey(
    User, on_delete=models.CASCADE, related_name="user_attendance", blank=False, null=True)
leave_reason = models.CharField(max_length=355, blank=True, null=True)
Date = models.DateField(blank=False, null=True,
                        auto_now=False, auto_now_add=True)
Presence = models.CharField(
    choices=Choices, max_length=255, blank=False, null=True)
attendance_taker = models.ForeignKey(
    User, on_delete=models.CASCADE, related_name="attendance_taker_attendance", blank=False, null=True)

def __str__(self):
    return f'{self.user}'

class Meta:
    verbose_name = _("Attendance")
    verbose_name_plural = _("Attendance")
    constraints = [
        UniqueConstraint(
            fields=('user', 'Date'), name='unique_attendance_once_per_date')
    ]

Attendance/serializers.py

class AttendanceSerializer(serializers.ModelSerializer):

class Meta:
    model = Attendance
    fields = ['user', 'Presence', 'leave_reason', 'Date']
    constraints = [
        UniqueConstraint(
            fields=('user', 'Date'), name='unique_attendance_once_per_date')
    ]

def create(self, validated_data):
    instance = Attendance.objects.create(
        user=validated_data['user'],
        Presence=validated_data['Presence'],
        leave_reason=validated_data['leave_reason'],
        attendance_taker=self.context['request'].user,
        Date=datetime.today
    )
    instance.save()
    return instance

Attendance/views.py

class AttendanceListCreateAPIView(CreateAPIView):
permission_classes = [IsClassPart]
queryset = Attendance.objects.all()
serializer_class = AttendanceSerializer

def post(self, request, format=None):
    user = request.user
    try:
        perms = Perm.objects.get(user=user)
    except ObjectDoesNotExist:
        perms = None
    serializer = AttendanceSerializer(data=request.data)
    if serializer.is_valid():
        if user.role == "TEACHER":
            if user.homeroom == serializer.validated_data['user'].room:
                Response({"message": "You don't have permission to perform this action 1"},
                         status=status.HTTP_400_BAD_REQUEST)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif perms is not None:
            if user.role != 'STUDENT' and user.perms.is_monitor:
                if user.room != serializer.validated_data['user'].room:
                    Response({"message": "You don't have permission to perform this action 2"},
                             status=status.HTTP_400_BAD_REQUEST)
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response({"message": "You don't have permission to perform this action 3"}, status=status.HTTP_400_BAD_REQUEST)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Postman test request

As you can see I'm sending user id, Presence=L(represents on leave) and leave_reason but the endpoint returns an empty {}

CodePudding user response:

I dont understand why you don't use user.has_perms(), but you forget any return on the if else block with perms check:

def post(self, request, format=None):
    user = request.user
    serializer = AttendanceSerializer(data=request.data)
    if serializer.is_valid():
        if user.role == "TEACHER":
            if user.homeroom == serializer.validated_data['user'].room:
                # Here error, without return
                return Response({"message": "You don't have permission to perform this action 1"},
                     status=status.HTTP_400_BAD_REQUEST)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif user.get_all_permissions():
            if user.role != 'STUDENT' and user.perms.is_monitor:
                if user.room != serializer.validated_data['user'].room:
                    # ERROR probably 
                    return Response({"message": "You don't have permission to perform this action 2"}, status=status.HTTP_400_BAD_REQUEST)

                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
             # error probably here too

        else:
            return Response({"message": "You don't have permission to perform this action 3"}, status=status.HTTP_400_BAD_REQUEST)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • Related