class ThesisBaseSerializer(ModelSerializer): state_label = CharField(source='get_state_display', read_only=True) authors = UserSerializer(read_only=True, many=True) supervisor = UserSerializer(read_only=True) opponent = UserSerializer(read_only=True) supervisor_id = PrimaryKeyRelatedField( write_only=True, source='supervisor', allow_null=True, required=False, queryset=User.school_users.teachers(), ) opponent_id = PrimaryKeyRelatedField( write_only=True, source='opponent', allow_null=True, required=False, queryset=User.school_users.teachers() ) class Meta: model = Thesis fields = ( 'id', 'title', 'abstract', 'state', 'state_label', 'authors', 'supervisor', 'supervisor_id', 'opponent', 'opponent_id', )
def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): token = request.data.get('token') expiration = request.data.get('expiration', '28800') if token and expiration.isdigit(): cache.set(f'{request.user.uuid}_brusafe', token, int(expiration)) return Response(UserSerializer(request.user).data) return Response(status=status.HTTP_400_BAD_REQUEST)
class AuditLogSerializer(ModelSerializer): id = IntegerField(source='event_id') timestamp = DateTimeField(source='action_tstamp_clk') action_label = CharField(source='get_action_display') user = UserSerializer() __table__ = CharField(source='table_name') __str__ = SerializerMethodField() table_name_to_verbose_name = keydefaultdict( lambda k: apps.get_model(k)._meta.verbose_name) class Meta: model = AuditLog fields = ( 'id', 'action', 'action_label', 'user', 'timestamp', 'row_data', 'changed_fields', '__table__', '__str__', ) @classmethod def get___str__(cls, obj: AuditLog): return cls.table_name_to_verbose_name[obj.model_name]
class DiagnosticSerializer(serializers.ModelSerializer): creator = serializers.CharField(read_only=True) user = UserSerializer(read_only=True) file_id = serializers.CharField(write_only=True, required=False) name = serializers.SerializerMethodField() class Meta: model = Diagnostic fields = ('name', 'creator', 'description', 'type', 'is_allergy', 'created', 'modified', 'id', 'file_id', 'user', 'diagnose', 'screening') def create(self, validated_data): file_id = get_id_by_file_id(validated_data['file_id']) if not file_id: raise serializers.ValidationError({'file_id': _('File not found')}) validated_data['file_id'] = file_id validated_data['creator'] = self._kwargs['context']['request'].user validated_data['user'] = self._kwargs['context']['request'].user return super().create(validated_data) def update(self, instance, validated_data): validated_data.pop('file_id', None) return super().update(instance, validated_data) @staticmethod def get_name(obj): if obj.is_screening: return obj.screening and obj.screening.term return obj.diagnose and obj.diagnose.term
def post(self, request, *args, **kwargs): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) token, created = Token.objects.get_or_create( user=serializer.validated_data.get('user')) serializer = UserSerializer(serializer.validated_data.get('user')) data = serializer.data data.update({"token": token.key}) return ShipmentSuccessResponse(data)
def create(self, request, *args, **kwargs): """ create get user's token """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user, token = serializer.save() user = UserSerializer(user).data data = {'user': user, 'token': token} return Response(data)
def post(self, request, *args, **kwargs): serializer = SignupSerializer(data=request.data) serializer.is_valid(raise_exception=True) user_obj = serializer.save() user_obj.set_password(serializer.validated_data.get('password')) user_obj.save() token, created = Token.objects.get_or_create(user=user_obj) serializer = UserSerializer(user_obj) data = serializer.data data.update({"token": token.key}) return ShipmentSuccessResponse(data)
class EvaluationsBaseSerializer(FileValidationMixin, serializers.ModelSerializer): survey_type = serializers.CharField(required=True) file = serializers.CharField(required=True) user = UserSerializer(read_only=True) class Meta: model = Evaluation fields = ('id', 'user', 'name', 'file', 'survey_results', 'is_editable', 'edited_by', 'survey_type') def create(self, validated_data): file_id = self.validated_data.get('file') file = get_file_by_file_id(file_id) survey_id = self.validated_data.get('survey_type') try: user = self.context.get('request')._user except AttributeError: user = None survey = None if survey_id: survey = get_survey_by_id(survey_id=int(survey_id)) if not survey: raise ValidationError("Survey does not exist.") if not check_user_permissions(user, survey.id): raise ValidationError("No permission.") validated_data.update({ 'survey_type': survey, 'name': survey.pk, 'file': file, 'user': user }) return super().create(validated_data) def update(self, instance, validated_data): try: user = self.context.get('request')._user except AttributeError: user = None if not check_user_permissions(user, instance.survey_type.id): raise ValidationError("No permission.") validated_data.update({ 'file': instance.file, 'survey_type': instance.survey_type, 'edited_by': user }) return super().update(instance, validated_data)
class PostSerializer(serializers.ModelSerializer): user = UserSerializer() is_liked = serializers.SerializerMethodField() class Meta: model = Post fields = ("id", "title", "description", "user", "is_liked") def get_is_liked(self, obj): user = self.context.get("request").user if user.is_anonymous: return None like = Like.objects.get_this_like(user, obj) if like is None: return None return like.like
class EmergencyContactSerializer(FileValidationMixin, serializers.ModelSerializer): file = serializers.CharField(required=True, write_only=True) patient = serializers.CharField(required=False, read_only=True) user = UserSerializer(read_only=True, source='creator') class Meta: model = EmergencyContact fields = ('file', 'patient', 'relation', 'name', 'phone', 'email', 'id', 'get_relation_display', 'trusted', 'user') def create(self, validated_data): file = get_file_by_file_id(validated_data.pop('file')) if file: validated_data['patient'] = get_file_by_file_id(file).patient validated_data['creator'] = self._kwargs['context']['request'].user return super().create(validated_data)
class VitalsSerializer(FileValidationMixin, serializers.ModelSerializer): file_id = serializers.CharField(write_only=True) file = serializers.CharField(source='file.file_id', read_only=True) user = UserSerializer(read_only=True) user_id = serializers.UUIDField(write_only=True) type = serializers.CharField(required=False) value = serializers.CharField(required=False) modified = serializers.SerializerMethodField() class Meta: model = VitalsParam fields = ('value', 'comment', 'type', 'user', 'user_id', 'file_id', 'file', 'id', 'created', 'modified') def get_modified(self, obj): created = obj.created + timedelta(seconds=1) if created < obj.modified: return obj.modified
class ArchiveCommentSerializer(FileValidationMixin, serializers.ModelSerializer): file_id = serializers.CharField(write_only=True) created_by = serializers.CharField(read_only=True) file = serializers.SerializerMethodField() user = UserSerializer(read_only=True) class Meta: model = ArchiveComment fields = ('comment', 'created', 'user', 'file_id', 'file', 'created_by') def create(self, validated_data): validated_data['user'] = self._kwargs['context']['request'].user return super().create(validated_data) @staticmethod def get_file(obj): return obj.file.file_id
class ReviewPublicSerializer(ModelSerializer): thesis = PrimaryKeyRelatedField( queryset=Thesis.objects.get_queryset(), style=dict(base_template='input.html'), ) user = UserSerializer(read_only=True) user_id = HiddenField(default=CurrentUserDefault(), source='user', write_only=True) url = HyperlinkedIdentityField(view_name='api:review-pdf-detail') created = DateTimeField(read_only=True, format=None) class Meta: model = Review fields = ( 'id', 'url', 'thesis', 'user', 'user_id', 'difficulty', 'grades', 'grade_proposal', 'created', ) def validate(self, attrs): thesis = attrs.get('thesis') user = self.context.get( 'request').user if not self.instance else self.instance.user if not (thesis.state == Thesis.State.READY_FOR_REVIEW and user in (thesis.supervisor, thesis.opponent) and not Review.objects.filter(thesis=thesis, user=user).exclude( id=self.instance.id if self.instance else None).exists()): raise ValidationError( _('Review has been already posted by this user or this user is not allowed to post ' 'review for this thesis.')) return attrs
def page_context(context, element_id, _re_language=re.compile(r'[_-]'), *args, **kwargs): request: HttpRequest = context['request'] user = request.user return json_script( dict(locale=_re_language.split(translation.get_language())[0], user=UserSerializer(instance=user).data, groups=tuple(user.groups.values_list('name', flat=True)), djangoAdminUrl=reverse('admin:index') if user.is_staff else '', logoutUrl=reverse('logout'), languages=[(k, translation.gettext(v)) for k, v in settings.LANGUAGES], version=settings.VERSION, messages=[ dict(text=str(m), type=m.level_tag) for m in get_messages(request) ]), element_id)
class ReservationSerializer(ModelSerializer): thesis_id = PrimaryKeyRelatedField( queryset=Thesis.objects.published(), source='thesis', style=dict(base_template='input.html'), ) user = UserSerializer(read_only=True) user_id = PrimaryKeyRelatedField( write_only=True, source='user', queryset=User.objects.all(), default=CurrentUserDefault(), style=dict(base_template='input.html'), ) thesis_label = CharField(source='thesis.__str__', read_only=True) thesis_registration_number = CharField(source='thesis.registration_number', read_only=True) state_label = CharField(source='get_state_display', read_only=True) class Meta: model = Reservation fields = ( 'id', 'thesis', 'thesis_id', 'user', 'user_id', 'thesis_label', 'thesis_registration_number', 'created', 'state', 'state_label', ) read_only_fields = ( 'thesis', 'created', )
class EvolutionSerializer(AwsUrlMixin, serializers.ModelSerializer): photo = Base64FileField(max_length=None, use_url=True, write_only=True, required=False, allow_null=True) photo_url = serializers.SerializerMethodField() thumb_url = serializers.SerializerMethodField() width = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2) height = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2) evolution_width = serializers.SerializerMethodField() evolution_height = serializers.SerializerMethodField() user = UserSerializer(read_only=True) class Meta: model = Evolution fields = ('width', 'height', 'evolution_width', 'evolution_height', 'photo_url', 'thumb_url', 'photo', 'wound', 'id', 'created', 'user') def create(self, validated_data): validated_data['user'] = self._kwargs['context']['request'].user return super().create(validated_data) def get_photo_url(self, obj): return self._get_aws_base64(obj.photo) if obj.photo else None def get_thumb_url(self, obj): return self._get_aws_base64(obj.thumbnail) if obj.thumbnail else None def get_evolution_width(self, obj): return obj.width def get_evolution_height(self, obj): return obj.height
class AboutPatientSerializer(ReadByMixin, serializers.ModelSerializer): file_id = serializers.SerializerMethodField() patient_id = serializers.SerializerMethodField() full_name = serializers.SerializerMethodField() user = UserSerializer() class Meta: model = AboutPatient fields = ( 'subject', 'msg_content', 'created', 'id', 'read_by', 'file_id', 'patient_id', 'full_name', 'user' ) @staticmethod def get_file_id(obj): return obj.file.file_id @staticmethod def get_patient_id(obj): return obj.file.patient.patient_id @staticmethod def get_full_name(obj): return obj.file.patient.full_name
class DocumentsSerializer(AwsUrlMixin, serializers.HyperlinkedModelSerializer): type_name = serializers.CharField(source='document_type.name', read_only=True) document_type = serializers.PrimaryKeyRelatedField(queryset=DocumentType.objects.all()) author = UserSerializer(read_only=True) url_link = serializers.HyperlinkedIdentityField(view_name='documents:download_pdf', read_only=True) parser_classes = (MultiPartParser, ) patient_file = serializers.CharField() extension = serializers.CharField(read_only=True) file = Base64FileField(max_length=None, use_url=True, required=True, allow_null=False) class Meta: model = Document fields = ('id', 'author', 'patient_file', 'name', 'file', 'url_link', 'document_type', 'type_name', 'created', 'extension') def validate(self, data): content = data.get('file', None) if content is None or content == "": raise serializers.ValidationError("Content is required") else: _, extension = os.path.splitext(content.name) # if extension not in ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.rtf']: # raise serializers.ValidationError("File is required, expected format: pdf, doc, docx, xls, xlsx, rtf") return data
class ListTodoSerializer(ModelSerializer): owner = UserSerializer() class Meta: model = Todo fields = ('__all__')
class LikeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Like fields = ("id", "like", "user")
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ScheduleSerializer(LocalStaticServe, serializers.ModelSerializer): patch_fields = ('date', 'members', 'comment', 'status', 'end_date', 'periodic', 'time') root_id = serializers.CharField(required=False, allow_null=True) initial_object = serializers.SerializerMethodField() task = serializers.SerializerMethodField() task_id = serializers.CharField(write_only=True, allow_null=True) left = serializers.SerializerMethodField() next = serializers.SerializerMethodField() mode = serializers.SerializerMethodField() periodic = serializers.CharField(required=False, write_only=True) users = serializers.SerializerMethodField() slot = serializers.BooleanField(required=False) end_time = serializers.SerializerMethodField() file_id = serializers.CharField(source='file.file_id', read_only=True) team_members = serializers.SerializerMethodField() user = UserSerializer(source='creator', read_only=True) icon = serializers.SerializerMethodField() all_members = None repeated_schedule = None class Meta: model = Schedule fields = ('date', 'time', 'comment', 'status', 'task', 'task_id', 'members', 'file', 'file_id', 'id', 'root_id', 'left', 'next', 'mode', 'periodic', 'users', 'slot', 'end_time', 'wound', 'team_members', 'prescription', 'creator', 'user', 'initial_object', 'icon') def get_icon(self, schedule): file = self.get_icon_file(schedule) if not file: default = static('tasks/icons/no-icon.png') return default if not self._is_local( ) else self._get_local_static_file(default) return file.replace('.svg', '-white.svg') def get_icon_file(self, obj): if obj.prescription: return static('tasks/icons/medication.svg')\ if not self._is_local() else self._get_local_static_file(static("tasks/icons/medication.svg")) if obj.task and obj.task.category and obj.task.category.icon: return static(obj.task.category.icon) \ if not self._is_local() else self._get_local_static_file(static(obj.task.category.icon)) if obj.task and obj.task.category and obj.task.category.image: return obj.task.category.image.url def get_task(self, obj): if not obj.task and obj.prescription: return PrescriptionLightSerializer(instance=obj.prescription).data return TaskSerializer(instance=obj.task).data def get_team_members(self, obj): return UserSerializer(obj.members.all(), many=True).data def validate_task_id(self, value): if value: task = get_task_by_id(value) if not task: raise serializers.ValidationError( _('Task id is not present in table "task"')) return value def get_end_time(self, obj): if obj.slot and obj.time: return f'{obj.time.hour + 2}:00:00' def get_users(self, obj): if not self.all_members: self.all_members = [(user.username, user.groups.first()) for user in obj.members.all()] return [ f'{username}({group.name if group else _("No group")})' for username, group in self.all_members ] def get_left(self, obj): if obj.root_id: tasks = [ task for task in self._kwargs['context']['_cached__schedules'] if task.root_id == obj.root_id ] return len([ task for task in tasks if datetime.combine(task.date, task.time) > datetime.now() ]) def get_next(self, obj): if obj.root_id: tasks = [ task for task in self._kwargs['context']['_cached__schedules'] if task.root_id == obj.root_id and datetime.combine(task.date, task.time) > datetime.combine( obj.date, obj.time) ] return datetime.strftime(tasks[0].date, '%d %b, %Y') if tasks else None def get_initial_object(self, obj): if obj.root_id: if not self.repeated_schedule: self.repeated_schedule = RepeatedTask.objects.filter( root_id=obj.root_id).first() if self.repeated_schedule: initial_data = { 'date': self.repeated_schedule.date, 'time': self.repeated_schedule.time, 'comment': self.repeated_schedule.comment, 'periodic': self.repeated_schedule.periodic, 'slot': self.repeated_schedule.slot, 'week_days': self.repeated_schedule.week_days, 'interval': self.repeated_schedule.interval, 'repeats': self.repeated_schedule.repeats, 'end_date': self.repeated_schedule.end_date, 'times': self.repeated_schedule.times } return initial_data def get_mode(self, obj): return obj.get_periodic_display() def update(self, instance, validated_data): validated_data = { field: validated_data[field] for field in self.patch_fields if validated_data.get(field) is not None } return super().update(instance, validated_data)
def get_team_members(self, obj): return UserSerializer(obj.members.all(), many=True).data
class WoundSerializer(FileValidationMixin, AwsUrlMixin, serializers.ModelSerializer): photo = serializers.CharField(write_only=True, required=False, allow_null=True) width = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2) height = serializers.DecimalField(write_only=True, max_digits=5, decimal_places=2) first_width = serializers.SerializerMethodField() first_height = serializers.SerializerMethodField() photo_url = serializers.SerializerMethodField() thumb_url = serializers.SerializerMethodField() file_id = serializers.CharField(write_only=True) file = serializers.CharField(source='file.file_id', read_only=True) treatment = serializers.SerializerMethodField() user = UserSerializer(read_only=True) class Meta: model = Wound fields = ('id', 'name', 'type', 'localization', 'is_cured', 'photo', 'width', 'height', 'first_width', 'first_height', 'photo_url', 'thumb_url', 'file', 'file_id', 'created', 'treatment', 'comment', 'user') def create(self, validated_data, **kwargs): data = { 'photo': validated_data.pop('photo', None), 'width': validated_data.pop('width'), 'height': validated_data.pop('height') } validated_data['user'] = self._kwargs['context']['request'].user wound = super().create(validated_data) data.update({'wound': wound.pk}) serializer = EvolutionSerializer(data=data, context=self._kwargs['context']) serializer.is_valid(raise_exception=True) serializer.save() return wound def get_first_width(self, obj): last = obj.evolution_set.last() if last: return last.width def get_first_height(self, obj): last = obj.evolution_set.last() if last: return last.height def get_photo_url(self, obj): last = obj.evolution_set.last() if last and last.photo: return self._get_aws_base64(last.photo) def get_thumb_url(self, obj): last = obj.evolution_set.last() if last and last.thumbnail: return self._get_aws_base64(last.thumbnail) def get_treatment(self, obj): task = obj.schedule_set.first() if task: return task.pk