def post(self, request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile, 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): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(raise_exception=True): profile = serializer.save() token, created = Token.objects.get_or_create(user=profile.user) return Response({'profile': serializer.data, 'token': token.key}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST )
def create_rating(request, movie_pk, user_pk): if request.method == 'POST': print(request.data, movie_pk, user_pk, 'asdjkfjsdkfj') # rating = request.body rating = request.data['rating'] user = User.objects.get(pk=user_pk + 2) print('user:'******'movie:', movie) profile = Profile.objects.get(pk=user_pk) timestamp = int(time.mktime(datetime.today().timetuple())) if profile not in movie.visited_user.all(): movie.visited_user.add(user_pk) movie.save() Rating(rating=rating, user=user, movie=movie, timestamp=timestamp).save() newrating = Rating.objects.filter(movie=movie_pk).aggregate( Avg('rating')) profile_serializer = ProfileSerializer(profile) return Response({ 'message': '평점 등록완료', 'data': newrating, 'visit': profile_serializer.data['user_visited'] }) else: print(user_pk, '이미있음') print('user', user_pk) print('vistied_user', movie.visited_user.all()) print(user_pk, '가 방문한 영화', Profile.objects.get(pk=user_pk).user_visited.all()) return Response(status=status.HTTP_409_CONFLICT)
def del_rating(request, movie_pk, user_pk): if request.method == 'POST': user = User.objects.get(pk=user_pk + 2) print(user) movie = Movie.objects.get(pk=movie_pk) movie.visited_user.remove(user_pk) print(user_pk, movie_pk, 'aaaaaaa') ratings = Rating.objects.filter(user=user_pk + 2) # slug 로 남겨야함 print('ratings', ratings) for rating in ratings: if rating.movie.pk == movie_pk: # rating.remove(movie_pk) print(rating.movie.pk, 'asd') rate = Rating.objects.get(pk=rating.pk) rate.delete() print(rating.pk) break # 하나만 삭제하고 나감 newrating = Rating.objects.filter(movie=movie_pk).aggregate( Avg('rating')) profile = Profile.objects.get(pk=user_pk) print(profile.__dict__) profile_serializer = ProfileSerializer(profile) # movie.save() return Response({ 'message': '평점삭제완료', 'data': newrating, 'visit': profile_serializer.data['user_visited'] })
class PatientSerializer(serializers.ModelSerializer): profile = ProfileSerializer(read_only=True) class Meta: model = Patient fields = ['id', 'profile', 'insurance_number'] extra_kwargs = {'id': {'read_only': True}}
def post(self, request): data = request.data response_data = {} response_data["success"] = True if not 'email' in data: response_data["message"] = _("email is required ") response_data["success"] = False return Response(data=response_data, status=status.HTTP_400_BAD_REQUEST) existUser = self.getObjectOrNone(User, email=data["email"]) if existUser is not None: response_data["success"] = False response_data["message"] = _("Email already in use") return Response(data=response_data, status=status.HTTP_206_PARTIAL_CONTENT) serializer = UserSerializer(data=data, many=False) if not serializer.is_valid(): response_data["success"] = False response_data["message"] = self.returnSerializerErrors(serializer.errors) return Response(data=response_data, status=status.HTTP_400_BAD_REQUEST) created_user = serializer.save() response_data = ProfileSerializer(created_user, many=False).data return Response(data=response_data, status=status.HTTP_201_CREATED)
def get_participants(self, obj): if obj.participants.count() > 0: result = [] for x in range(obj.participants.count()): serializer = ProfileSerializer(obj.participants.all()[x]) result.append(serializer.data) return result return None
def update(self, request, *args, **kwargs): profile = self.get_object() serializer = ProfileUpdateSerializer(profile, data=request.data) if serializer.is_valid(): serializer.save() profile.refresh_from_db() serializer = ProfileSerializer(profile) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class HealthCareWorkerSerializer(serializers.ModelSerializer): access_time = AccessTimesSerializer(read_only=True) profile = ProfileSerializer(read_only=True) class Meta: model = HealthCareWorker fields = [ 'identifier', 'professional_card', 'works_at', 'access_time', 'profile', 'worker_type' ] extra_kwargs = {'access_time': {"required": False}}
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data token = Token.objects.get(user=user).key profile = user.profile return Response({ "token": token, "profile": ProfileSerializer(profile).data })
def me(self, request): user_id = request.user.id try: my_profile = Profile.objects.get(user_id=user_id) except Profile.DoesNotExist: return Response( data={'error': 'User still not create personal profile!'}, status=status.HTTP_400_BAD_REQUEST) serializer = ProfileSerializer(my_profile) return Response(serializer.data, status=status.HTTP_200_OK)
def UserbyToken(request, user=None): #token에서 user_id 추출하기 token = request.headers['Authorization'][4:] payload = jwt.decode(token, JWT_AUTH['JWT_SECRET_KEY'], JWT_AUTH['JWT_ALGORITHM']) id_token = int(payload['user_id']) #user_id로 프로필정보 뽑아내기 queryset = Profile.objects.all().filter(user_id=id_token) serializer = ProfileSerializer(queryset, many=True) return Response(serializer.data)
def create(self, request, *args, **kwargs): password = request.data.pop('password') serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() user.set_password(password) user.save() assign_crud_permissions(user, user) headers = self.get_success_headers(serializer.data) account = authenticate(username=user.email, password=password) response = Response(ProfileSerializer(user, context={'request': request}).data, status=status.HTTP_201_CREATED) response = set_jwt_token(response, account) login(request, account) return response
def user_detail(user: User, user_details: UserDetails): try: token = user.auth_token.key except: token = Token.objects.create(user=user) token = token.key user_json = { "user_id": user.user_id, "token": token, } if user_details: user_json.update( {'user_details': ProfileSerializer(instance=user_details).data}) return user_json
def post(self, request, *args, **kwargs): user = request.user profile = user.userAssociated.all().first() try: if user.auth_provider == "email": raise ValidationError( "You must be the social user to use this API") full_name = request.data.get('full_name') country = request.data.get('country').lower() city = request.data.get('city').lower() gender = request.data.get('gender') if (full_name == "" or country == "") or ("full_name" not in request.data or "country" not in request.data): raise ValidationError("full name and country are mandatory") profile = Profile.objects.filter(id=profile.id) profile_user = profile.first() profile.update(full_name=full_name, country=country, city=city, gender=gender) except Exception as e: response = { "message": "Profile creation failed", "error": str(e), "status": HTTP_400_BAD_REQUEST } return Response(response, status=HTTP_400_BAD_REQUEST) profile = Profile.objects.filter(id=profile_user.id).first() data = ProfileSerializer(profile).data response = { "message": "Profile created for social user successfully", "body": data, "status": HTTP_200_OK } return Response(response, status=HTTP_200_OK)
def get_player_rank_info(request, delta=None, count=10, relative=False, target_player=None): """ Get verbose rank information for players in rank range. Args: request: Request object from view. Required for serializer context. delta: Time delta (backwards from the current moment) to start counting scores from count: The number of player records to return relative: target_player: The central player to get records relative to Returns: list: """ rank_info = [] rank_to_player, player_pk_to_rank, rank_to_score = get_all_player_ranks(delta=delta) ranks = sorted(list(rank_to_player.keys())) if relative: # Target behavior is to return (count // 2) above and (count // 2 - 1) below assert target_player is not None player_rank = player_pk_to_rank[target_player.pk] rank_index = ranks.index(player_rank) target_below = int(round(count / 2 + eps)) target_above = int(round(count / 2 + eps)) - (count % 2) below = rank_index above = len(ranks) - rank_index if above < target_above: target_below += target_above - above elif below < target_below: target_above += target_below - below ranks = ranks[max(0, rank_index - target_below):max(0, rank_index + target_above)] else: ranks = ranks[:count] for rank in ranks: player = rank_to_player[rank] profile = player.user.profile data = { 'rank': rank, 'profile': ProfileSerializer(profile, context={'request': request}).data, 'username': player.user.username, 'score': rank_to_score[rank], 'skill_rating': player.skill_rating } rank_info.append(data) return rank_info
def jwt_response_payload_handler(token, user=None, request=None): """ Returns the response data for both the login and refresh views. Override to return a custom response such as including the serialized representation of the User. Example: def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data } """ return { 'token': token, 'user': ProfileSerializer(user, context={ 'request': request }).data }
def post(self, request): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] # # Account into request.data.update({'preferences': {'wtf': ''}}) request.data.update({'user': user.id}) profile = ProfileSerializer(user.profile) token, created = Token.objects.get_or_create(user=user) accountInfo = { 'token': token.key, 'username': user.username, 'profile': profile.data } return Response(accountInfo)
def get(self, request): response_data = ProfileSerializer(request.user, many=False).data return Response(data=response_data, status=status.HTTP_200_OK)
def get_profile_info(self, obj): return ProfileSerializer(obj.profile).data
def register_social_user(provider, user_id, email, name): filtered_user_by_email = User.objects.filter(email=email) if filtered_user_by_email.exists(): if provider == filtered_user_by_email[0].auth_provider: registered_user = authenticate( email=email, password=config('SOCIAL_SECRET')) try: token = Token.objects.get(user=registered_user).key print(token) if token is None: raise Http404 except: return { 'message':'Login Failed !!', 'error':'Invalid Token', 'status':HTTP_401_UNAUTHORIZED } profile = registered_user.userAssociated.all().first() data = ProfileSerializer(profile).data data["token"] = token try: current_site = CustomConstants.EMAIL_DOMAIN request_url = CustomConstants.NODE_SERVER_DOMAIN + 'user/score/' node_response = requests.get( request_url, headers={ 'x-auth-server': CustomConstants.NODE_ADMIN_TOKEN, 'Content-Type':"application/json", }, json={ 'userID': profile.pk, } ) user_score_response = node_response.json() node_response.raise_for_status() data['userScore'] = user_score_response['score'] return data except Exception as e: raise AuthenticationFailed(str(e)) else: raise AuthenticationFailed( detail='Please continue your login using ' + filtered_user_by_email[0].auth_provider) else: user = { 'username': generate_username(name), 'email': email, 'password': config('SOCIAL_SECRET')} user = User.objects.create_user(**user) user.is_verified = True user.auth_provider = provider user.save() print(user) try: token = Token.objects.get(user=user).key if token is None: raise Http404 except: return { 'message':'Login Failed !!', 'error':'Invalid Token', 'status':HTTP_401_UNAUTHORIZED } new_user = authenticate( email=email, password=config('SOCIAL_SECRET')) return { 'email': new_user.email, 'username': new_user.username, "token": token }
def get(self, request, pk, format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data)
def get(self, request, format=None): user = request.user profile = Profile.objects.get(user=user) serialized = ProfileSerializer(profile, many=False).data return Response(serialized)
def get(request): profiles = Profile.objects.filter(visit_counter__gte=1).order_by("-visit_counter") serializers = ProfileSerializer(profiles,many=True) return Response(serializers.data)
def set_profile(self, obj, user): profile = ProfileSerializer(user, context={'request': self.context['request']}).data fields = [ 'id', 'first_name', 'last_name', 'photo_url', 'roles', 'city', 'state', 'country', 'verification' ] return { k: v for k, v in profile.items() if k in fields }
def get(self, request, format=None): return Response({ 'profile': ProfileSerializer(request.user.profile).data })
def get_winner(self, obj): if obj.winner is not None: profile = Profile.objects.get(id=obj.winner.id) serializer = ProfileSerializer(profile) return serializer.data return None
def get_owner(self, obj): profile = Profile.objects.get(id=obj.owner.id) serializer = ProfileSerializer(profile) return serializer.data