def test_patch_update_age(self): """test update user's age""" edited_user = User.objects.get(pk=self.test_user.pk) edited_user.age = 41 response = self.client.patch( USERS_PROFILE_DATA_URL % self.hashed_user_id, {'age': edited_user.age} ) serializer_edited_user = UserSerializer(edited_user) expected = serializer_edited_user.data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(expected, response.data) serializer = UserSerializer(self.test_user) self.assertNotEqual(serializer.data, response.data) self.assertIn(edited_user, User.objects.all()) # age == 'null' edited_user = User.objects.get(pk=self.test_user.pk) edited_user.age = None response = self.client.patch( USERS_PROFILE_DATA_URL % self.hashed_user_id, {'age': ''} ) serializer_edited_user = UserSerializer(edited_user) expected = serializer_edited_user.data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(expected, response.data) serializer = UserSerializer(self.test_user) self.assertNotEqual(serializer.data, response.data) self.assertIn(edited_user, User.objects.all())
def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() login(request, user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): self.check_permissions(request) serializer = UserSerializer(data=request.data) if serializer.is_valid(): new_user = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def api_create_users_view(request): user = User() if request.method == "POST": 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)
def update(self, request, pk): self.check_permissions(request) user = get_object_or_404(User, pk=pk) self.check_object_permissions(request, user) serializer = UserSerializer(instance=user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, *args, **kwargs): user = User.objects.get(id = request.data.get('id')) sector = request.data.get('sector') image = request.data.get('image') user.username = request.data.get('username') user.email = request.data.get('email') user.name = request.data.get('name') user.ramal = request.data.get('ramal') user.description = request.data.get('description') if sector == None or sector == '' or sector is None: user.sector = None else: sector = Sector.objects.get(id = request.data.get('sector')) user.sector = sector if image == None or image == '' or image is None: pass else: image = Image.objects.get(id = request.data.get('image')) user.image = image if request.data.get('is_administrator') is None: user.is_administrator = False else: user.is_administrator = True if request.data.get('is_participant') is None: user.is_participant = False else: user.is_participant = True if user.is_administrator == True: user.is_participant = False user.is_staff = True user.is_superuser = True user.is_active = True else: user.is_participant = True user.is_staff = False user.is_superuser = False user.is_active = True user.save() serializer = UserSerializer(instance = user, data = request.data) serializer.is_valid(raise_exception = True) self.perform_update(serializer) return Response(serializer.data)
def registration_view(request): serializer = UserSerializer(data=request.data) response = {} if serializer.is_valid(): account = serializer.save() # token = Token.objects.create(user=account) response['status'] = 'success' response['message'] = 'account registered successfully' # response['token'] = token.key else: data = serializer.errors return Response(response)
def post(self, request): data = request.data user_serializer = UserSerializer(data=request.data, context={'request': request}) if user_serializer.is_valid(raise_exception=True): user = user_serializer.save() return Response(data, status=status.HTTP_200_OK) else: return Response( { 'status': False, 'message': msgs.INVALID_EMAIL_OR_PASSWORD }, status=status.HTTP_400_BAD_REQUEST)
def api_update_users_view(request, id): try: user = User.objects.get(pk=id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "PUT": serializer = UserSerializer(user, data=request.data) data = {} if serializer.is_valid(): serializer.save() data = serializer.data data["message"] = "User updated successfully." return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def roommate(self, request): """ Advanced function 2 - Potential Roommates Find 2 users from a same department and have both liked 3 or more same houses. Sample query: SELECT user_id FROM users_userprofile WHERE department_id = 34 AND user_id != 1 AND (SELECT count(*) FROM ((SELECT house_id_id FROM like_like WHERE user_id_id = user_id AND has_liked = TRUE) INTERSECT (SELECT house_id_id FROM like_like WHERE user_id_id = 1 AND has_liked = TRUE)) as same) >= 3; """ user = request.user if not user.profile: return None user_department_id = user.profile.department_id roommate_query = 'SELECT * FROM users_userprofile WHERE department_id = %s AND user_id != %s AND' % ( user_department_id, user.id) user_like_query = '(SELECT house_id_id FROM like_like WHERE user_id_id = %s AND has_liked = TRUE)' % user.id roommate_like_query = '(SELECT house_id_id FROM like_like WHERE user_id_id = user_id AND has_liked = TRUE)' judge_query = '(SELECT count(*) FROM (%s INTERSECT %s) AS same) >= 3' % ( user_like_query, roommate_like_query) roommate_query = roommate_query + judge_query user_queryset = UserProfile.objects.raw(roommate_query) return Response( [UserSerializer(profile.user).data for profile in user_queryset])
def create_auth_response(body, headers, status, data={}): if not check_captcha(data): body = "Captcha is not correct!" status = status_code.HTTP_400_BAD_REQUEST if status == status_code.HTTP_200_OK: loaded_body = json.loads(body) access_token = loaded_body.get('access_token') refresh_token = loaded_body.get('refresh_token') user = repository.get_user_by_access_token(access_token) payload = json.dumps(UserSerializer(user).data) response = HttpResponse(content=payload, status=status) response = helpers.set_auth_cookie(response, access_token, refresh_token) users.repository.send_signal(action=LOGIN, status_code=status, user=user) else: username = data.get('username') user = get_user_by_username(username) body = "Password or username is not correct!" if user: users.repository.send_signal(action=LOGIN, status_code=status, username=username) status = get_fail_status(status, user) lock_or_catpcha(status, user, username) response = HttpResponse(content=body, status=status) for k, v in headers.items(): response[k] = v return response
def get(self, request, format=None): """ List rooms with recent conversations """ # get recent rooms qs_rooms = request.user.rooms.all().order_by('-last_activity')[:10] room_serializer = RoomSerializer(qs_rooms, context={'request': request}, many=True) # get relations of the rooms participants = set() messages = set() for room_data in room_serializer.data: participants = participants.union(set(room_data['participants'])) messages.add(room_data['last_message']) # build relation responses participants_obj = User.objects.filter(id__in=participants) users_serializer = UserSerializer(participants_obj, many=True) messages_obj = Message.objects.filter(id__in=messages) messages_serializer = MessageSerializer(messages_obj, context={'request': request}, many=True) # combine response return Response({ 'rooms': room_serializer.data, 'messages': messages_serializer.data, 'users': users_serializer.data })
def get(self, request, room_id, format=None): """ List rooms with recent conversations """ # get room room = get_object_or_404(request.user.rooms.all(), id=room_id) room_serializer = RoomSerializer(room, context={'request': request}) # get messages offset = self.request.query_params.get('offset') offset = int(offset) if offset else None if offset: messages = room.messages \ .filter(id__lt=offset) \ .order_by('-id')[:10][::-1] else: messages = room.messages.order_by('-timestamp')[:10][::-1] messages_serializer = MessageSerializer(messages, context={'request': request}, many=True) # get participants participants = set() for message in messages_serializer.data: participants.add(message['author']) participants_obj = User.objects.filter(id__in=participants) users_serializer = UserSerializer(participants_obj, many=True) # combine response return Response({ 'messages': messages_serializer.data, 'room': room_serializer.data, 'users': users_serializer.data, })
def list(self, request): """ List user's pending to receive messages """ pending_messages_qs = Message.objects\ .get_pending_messages(request.user) messages_serializer = MessageSerializer(pending_messages_qs, context={'request': request}, many=True) # get relations of the rooms rooms = set() for message_data in messages_serializer.data: rooms.add(message_data['room']) rooms_obj = Room.objects.filter(id__in=rooms) rooms_serializer = RoomSerializer(rooms_obj, context={'request': request}, many=True) # get relations of the users users = set() for room_data in rooms_serializer.data: users = users.union(set(room_data['participants'])) users_obj = User.objects.filter(id__in=users) users_serializer = UserSerializer(users_obj, many=True) # combine response return Response({ 'messages': messages_serializer.data, 'rooms': rooms_serializer.data, 'users': users_serializer.data, })
def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) serializer_users = serializer.data rendered = JSONRenderer() json_user = rendered.render(serializer_users) return HttpResponse(json_user)
class PostSerializer(serializers.ModelSerializer): #fetch data from users model and return them as fields in the Post model #the below fields are present in the User model and are connected to the User model via get_created_by #created_by is a foreignkey relationship between Post and User model #get a sub array of user information by linking profile with UserSerializer stdlogger.info("associate post with a user model") profile = UserSerializer(read_only=True, source='created_by') #categories returns a list of api urls incase the user would like to modify the category title #categories field must exist in the Post model as manytomany relation stdlogger.info("associate post with multiple categories") categories = CategorySerializer(many=True) stdlogger.info("associate post with multiple comments") comments = CommentSerializer(many=True) stdlogger.info("Alter date format") created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") class Meta: model = Post #depth = 1 #fields are a mix of fields present in Post , Categories, and User models fields = ('id', 'title', 'categories', 'slug', 'content', 'created_by', 'updated_by', 'pstatus', 'created_at', 'updated_at', 'comments', 'profile', 'total_comments')
def list(self, request): """ List rooms in which the current user is a participant """ # get all rooms qs_rooms = request.user.rooms.all() room_serializer = RoomSerializer(qs_rooms, context={'request': request}, many=True) # get relations of the rooms participants = set() messages = set() for room_data in room_serializer.data: participants = participants.union(set(room_data['participants'])) messages.add(room_data['last_message']) # build participants response participants_obj = User.objects.filter(id__in=participants) users_serializer = UserSerializer(participants_obj, many=True) # build messages response messages_obj = Message.objects.filter(id__in=messages) messages_serializer = MessageSerializer(messages_obj, context={'request': request}, many=True) # combine response return Response({ 'rooms': room_serializer.data, 'messages': messages_serializer.data, 'users': users_serializer.data })
def get(self, request): try: user = request.user serializer = UserSerializer(user) return Response(serializer.data, status.HTTP_200_OK) except Exception: return Response({"results": "Error There is error on request"}, status.HTTP_400_BAD_REQUEST)
def retrieve(self, request, pk): # si no tiene permisos no realiza petición a la BD self.check_permissions(request) user = get_object_or_404(User, pk=pk) # tiene permiso dicho usuario self.check_object_permissions(request, user) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_201_CREATED)
def get_group_profile(self, obj): if obj.kind == 1: # If private then return name of the other participant current_user = self.context['request'].user participants = list(obj.participants.all()) participants.remove(current_user) return UserSerializer(participants[0]).data return obj.group_name
def test_list_users(self): users = User.objects.all() request = self.factory.get('/') serializer = UserSerializer(users, context={'request': request}, many=True) response = self.client.get(reverse('api:user-list')) self.assertEqual(response.data, serializer.data)
def get_user_info(self, request): key = request.query_params.get('key', '') if not key: return Response({'detail': '请传入用户的key'}, status=status.HTTP_400_BAD_REQUEST) user = Token.objects.get(key=key).user serializer = UserSerializer(user) return Response(serializer.data)
class LectureSerializer(serializers.ModelSerializer): lecture = UserSerializer() class Meta: model = Lecture fields = [ 'lecture', 'main_lecture', ]
def api_detail_users_view(request, id): try: user = User.objects.get(pk=id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = UserSerializer(user) return Response(serializer.data)
def get(self, request, format=None): email = request.query_params.get('email', None) if email is not None: users = User.objects.filter(username__istartswith=email) serializer = UserSerializer(users, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST)
class ChatMessageSerializer(serializers.ModelSerializer): """ Serializer for chat message model for api """ author = UserSerializer(read_only=True) class Meta: model = ChatMessage fields = ('id', 'maint_request', 'author', 'message', 'date_posted')
def partial_update(self, request, *args, **kwargs): queryset = PasswordReset.objects.all() email_object = get_object_or_404(queryset, token=request.data['token']) if datetime.now().date() - email_object.created_at.date() < timedelta(hours=2): email_object = PasswordResetSerializer(email_object) user = User.objects.get(email=email_object.data['email']) new_data = { "password": request.data['password'] } user = UserSerializer(user, data=new_data, partial=True) if user.is_valid(): user.save() PasswordReset.objects.filter(token=request.data['token']).delete() return Response(user.data, status=201) else: return Response(user.errors, status=403) return Response(status=200) else: return Response(status=403)
class TaskSerializer(serializers.ModelSerializer): taskusers = TaskUserSerializer(source='taskuser_set', many=True) user = UserSerializer(read_only=True) class Meta: model = Task fields = [ 'id', 'name', 'description', 'reward', 'user', 'taskusers', 'date_added' ]
def test_get(self): """test if user exists""" response = self.client.get(USERS_PROFILE_URL % self.hashed_user_id) serializer = UserSerializer(self.test_user) expected = serializer.data expected['enable_editing_profile'] = True self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertDictEqual(expected, response.data)
class ProjectSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only=True) class Meta: model = Project fields = ['title', 'description', 'status', 'start_date', 'end_date', 'url', 'users'] extra_kwargs = { 'url': {'view_name': 'api:project-detail', 'lookup_field': 'id'} }