def create(self, request, *args, **kwargs): try: serializer = LocationSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) if serializer.is_valid(): serializer.save() headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) except serializers.ValidationError: print(traceback.print_exc()) raise except ValidationError as e: if hasattr(e, 'error_dict'): raise serializers.ValidationError(repr(e.error_dict)) else: # raise serializers.ValidationError(repr(e[0].encode('utf-8'))) raise serializers.ValidationError(repr(e[0])) except Exception as e: print(traceback.print_exc()) raise serializers.ValidationError(str(e))
def save_location(location_request_data, *args, **kwargs): try: if location_request_data.get('id'): location_instance = Location.objects.get( id=location_request_data.get('id')) location_serializer = LocationSerializer( instance=location_instance, data=location_request_data, partial=True ) location_serializer.is_valid(raise_exception=True) if location_serializer.is_valid(): location_serializer.save() else: location_serializer = LocationSerializer( data=location_request_data, partial=True ) location_serializer.is_valid(raise_exception=True) if location_serializer.is_valid(): location_instance = location_serializer.save() return location_serializer.data except serializers.ValidationError: print(traceback.print_exc()) raise except ValidationError as e: if hasattr(e, 'error_dict'): raise serializers.ValidationError(repr(e.error_dict)) else: # raise serializers.ValidationError(repr(e[0].encode('utf-8'))) raise serializers.ValidationError(repr(e[0])) except Exception as e: print(traceback.print_exc()) raise serializers.ValidationError(str(e))
class InspectionSerializer(serializers.ModelSerializer): allocated_group = serializers.SerializerMethodField() inspection_team = serializers.SerializerMethodField() all_officers = serializers.SerializerMethodField() user_in_group = serializers.SerializerMethodField() can_user_action = serializers.SerializerMethodField() user_is_assignee = serializers.SerializerMethodField() status = CustomChoiceField(read_only=True) #inspection_team = EmailUserSerializer(many=True, read_only=True) individual_inspected = IndividualSerializer() organisation_inspected = OrganisationSerializer(read_only=True) #inspection_type = InspectionTypeSerializer() related_items = serializers.SerializerMethodField() inspection_report = serializers.SerializerMethodField() data = InspectionFormDataRecordSerializer(many=True) location = LocationSerializer(read_only=True) class Meta: model = Inspection fields = ( 'id', 'number', 'status', 'title', 'details', 'planned_for_date', 'planned_for_time', 'party_inspected', 'assigned_to_id', 'allocated_group', 'allocated_group_id', 'user_in_group', 'can_user_action', 'user_is_assignee', 'inspection_type_id', 'inspection_team', 'inspection_team_lead_id', 'individual_inspected', 'organisation_inspected', 'individual_inspected_id', 'organisation_inspected_id', 'related_items', 'inform_party_being_inspected', 'call_email_id', 'legal_case_id', 'inspection_report', 'schema', 'region_id', 'district_id', 'data', 'all_officers', 'location', ) read_only_fields = ('id', ) def get_related_items(self, obj): return get_related_items(obj) def get_user_in_group(self, obj): return_val = False user_id = self.context.get('request', {}).user.id # inspection team should apply if status is 'open' if obj.status == 'open' and obj.inspection_team: for member in obj.inspection_team.all(): if user_id == member.id: return_val = True elif obj.allocated_group: for member in obj.allocated_group.members: if user_id == member.id: return_val = True return return_val def get_can_user_action(self, obj): return_val = False user_id = self.context.get('request', {}).user.id if user_id == obj.assigned_to_id: return_val = True if obj.status == 'open' and obj.inspection_team and not obj.assigned_to_id: for member in obj.inspection_team.all(): if user_id == member.id: return_val = True elif obj.allocated_group and not obj.assigned_to_id: for member in obj.allocated_group.members: if user_id == member.id: return_val = True return return_val def get_user_is_assignee(self, obj): return_val = False user_id = self.context.get('request', {}).user.id if user_id == obj.assigned_to_id: return_val = True return return_val def get_inspection_team(self, obj): team = [{'id': None, 'full_name': '', 'member_role': '', 'action': ''}] returned_inspection_team = EmailUserSerializer( obj.inspection_team.all(), context={'inspection_team_lead_id': obj.inspection_team_lead_id}, many=True) for member in returned_inspection_team.data: team.append(member) return team def get_allocated_group(self, obj): return '' #allocated_group = [{ # 'email': '', # 'first_name': '', # 'full_name': '', # 'id': None, # 'last_name': '', # 'title': '', # }] #returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group) #for member in returned_allocated_group.data['members']: # allocated_group.append(member) #return allocated_group def get_all_officers(self, obj): return [] #all_officer_objs = [] #compliance_content_type = ContentType.objects.get(model="compliancepermissiongroup") #permission = Permission.objects.filter(codename='officer').filter(content_type_id=compliance_content_type.id).first() #for group in permission.group_set.all(): # for user in group.user_set.all(): # all_officer_objs.append(user) #unique_officers = list(set(all_officer_objs)) #sorted_unique_officers = sorted(unique_officers, key=lambda officer: officer.last_name) #serialized_officers = IndividualSerializer(sorted_unique_officers, many=True) #returned_data = serialized_officers.data #blank_field = [{ # 'dob': '', # 'email': '', # 'full_name': '', # 'id': None, # }] #returned_data.insert(0, blank_field) #print(returned_data) #return returned_data def get_inspection_report(self, obj): return [[r.name, r._file.url] for r in obj.report.all()]
class OffenceSerializer(serializers.ModelSerializer): status = CustomChoiceField(read_only=True) location = LocationSerializer(read_only=True) alleged_offences = serializers.SerializerMethodField() offenders = serializers.SerializerMethodField() allocated_group = serializers.SerializerMethodField() user_in_group = serializers.SerializerMethodField() can_user_action = serializers.SerializerMethodField() # can_user_edit = serializers.SerializerMethodField() user_is_assignee = serializers.SerializerMethodField() related_items = serializers.SerializerMethodField() in_editable_status = serializers.SerializerMethodField() user_action = serializers.SerializerMethodField() class Meta: model = Offence fields = ( 'id', 'identifier', 'lodgement_number', 'status', 'legal_case_id', 'call_email', # TODO: should be call_email_id ? 'region_id', 'district_id', 'assigned_to_id', 'allocated_group', 'allocated_group_id', 'user_in_group', 'can_user_action', # 'can_user_edit', 'user_is_assignee', 'related_items', 'district', 'inspection_id', 'occurrence_from_to', 'occurrence_datetime_from', 'occurrence_datetime_to', 'details', 'location', 'alleged_offences', 'offenders', 'in_editable_status', 'user_action', ) read_only_fields = ( ) def get_user_action(self, obj): return get_user_action(self, obj) def get_in_editable_status(self, obj): return obj.status in (Offence.STATUS_DRAFT, Offence.STATUS_OPEN) def get_alleged_offences(self, offence): alleged_offences = AllegedOffence.objects.filter(offence=offence) ret_list = [] for alleged_offence in alleged_offences: ret_obj = {} section_regulation_serializer = SectionRegulationSerializer(alleged_offence.section_regulation) ret_obj['section_regulation'] = section_regulation_serializer.data ret_obj['id'] = alleged_offence.id ret_obj['removed'] = alleged_offence.removed ret_obj['removed_by_id'] = alleged_offence.removed_by.id if alleged_offence.removed_by else None ret_obj['reason_for_removal'] = alleged_offence.reason_for_removal # number_linked_to_sanction_outcomes ret_obj['number_linked_sanction_outcomes_total'] = AllegedCommittedOffence.objects.filter( Q(alleged_offence=alleged_offence) ).count() # number_linked_to_sanction_outcomes which includes alleged offence and its status is other than draft qs = AllegedCommittedOffence.get_active_alleged_committed_offences(alleged_offence) ret_obj['number_linked_sanction_outcomes_active'] = qs.count() connected_offenders = [] for aco in qs: if aco.sanction_outcome and aco.sanction_outcome.offender: serializer = EmailUserSerializer(aco.sanction_outcome.offender.person) connected_offenders.append(serializer.data) ret_obj['connected_offenders'] = connected_offenders ret_list.append(ret_obj) return ret_list def get_offenders(self, obj): offenders = Offender.objects.filter(offence__exact=obj) offenders_list = [ OffenderSerializer(offender).data for offender in offenders ] return offenders_list def get_allocated_group(self, obj): allocated_group = [{ 'email': '', 'first_name': '', 'full_name': '', 'id': None, 'last_name': '', 'title': '', }] returned_allocated_group = CompliancePermissionGroupMembersSerializer(instance=obj.allocated_group) for member in returned_allocated_group.data['members']: allocated_group.append(member) return allocated_group def get_user_in_group(self, obj): user_id = self.context.get('request', {}).user.id if obj.allocated_group: for member in obj.allocated_group.members: if user_id == member.id: return True return False # def get_can_user_edit(self, obj): # can_edit = False # if self.get_can_user_action(obj): # if obj.status in Offence.EDITABLE_STATUSES: # can_edit = True # return can_edit def get_can_user_action(self, obj): # User can have action buttons # when user is assigned to the target object or # when user is a member of the allocated group and no one is assigned to the target object user_id = self.context.get('request', {}).user.id if user_id == obj.assigned_to_id: return True elif obj.allocated_group and not obj.assigned_to_id: if user_id in [member.id for member in obj.allocated_group.members]: return True return False def get_user_is_assignee(self, obj): user_id = self.context.get('request', {}).user.id if user_id == obj.assigned_to_id: return True return False def get_related_items(self, obj): return get_related_items(obj)