Home > Enterprise >  Django: how to get the user from user form input
Django: how to get the user from user form input

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, I am trying to get some user details from the user that is being marked as present, absent, or on leave

serializer.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

my current implementation of the view:

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 == request.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 != request.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)

the error is in request.data['user'].room: as django says 'str' object has no attribute 'room'

CodePudding user response:

Try to access to serializer.validated_data for getting user instance:

    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)

Your request.data contains only data sent to the view in str variables. validated_data contains cleaned data from serializer with retrieve instance associated to foreign key if your model is correctly set

  • Related