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 put(self, request, pk): user = self.set_object(pk) user_json = UserSerializer(user, data = request.data) if user_json.is_valid(): user_json.save() return Response(user_json.data) return Response(user_json.data, status = 400)
class TripSerializer(PublicIdBaseSerializer): owner = UserSerializer() members = UserSerializer(many=True) destinations = DestinationSerializer(source='get_destinations', many=True) class Meta: model = Trip exclude = ('uid', )
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = User.objects.create_user(serializer.data['email'], serializer.data['password']) return Response({'token': user.token}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class FriendRequestSerializer(serializers.ModelSerializer): """ Serializer used for listing friend requests """ requester = UserSerializer() receiver = UserSerializer() class Meta: model = FriendRequest fields = ['id', 'requester', 'receiver', 'status'] read_only_fields = ['id', 'requester', 'receiver']
def post(self, request): try: serializer = UserSerializer(data=request.data) print(serializer.initial_data) if serializer.is_valid(): print(serializer.data) return Response("Done") else: print(serializer.errors) return Response("Not Done") except Exception as e: return Response(str(e))
class TripSerializerSimple(PublicIdBaseSerializer): owner = UserSerializer() members = UserSerializer(many=True) class Meta: model = Trip fields = ( 'id', 'title', 'tag_line', 'owner', 'members', 'created', 'modified', )
def list(self, request): queryset = self.get_queryset() qs = AccountUser.objects.all().exclude(id=self.request.user.id) total_users = len(qs) params = self.request.query_params order = params.get("order", None) order_by = params.get("orderBy", None) if order is not None: if order == 'asc': qs = AccountUser.objects.order_by(F(order_by).asc()) else: qs = AccountUser.objects.order_by(F(order_by).desc()) if params.get("page", None) is not None: if self.request.user.role == "manager": qs = qs.exclude(role="admin") total_users = len(qs) serializer = UserSerializer(queryset, many=True) return Response(data={ "total_users": total_users, "data": serializer.data })
def login(request): phone = request.data.get("phone") sms_code = request.data.get("sms_code") phone_type = request.data.get("phone_type") registration_id = request.data.get("registration_id") try: user = User.objects.get(phone=phone) except: raise AuthenticationFailed({"phone": ["phone doesn't exist"]}) if not user.sms_code: raise AuthenticationFailed({"sms": ["sms didn't send"]}, ) if user.sms_code != sms_code: raise AuthenticationFailed({"sms": ["sms not correct"]}) now = datetime.datetime.utcnow().replace(tzinfo=utc) delta = now - user.modified if delta > datetime.timedelta(minutes=2): raise AuthenticationFailed({"sms": ["sms code expired"]}) user.sms_code = None user.save() serializer = UserSerializer(user, context={"request": request}) data = serializer.data payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) update_last_login(None, user) data['token'] = token.decode('unicode_escape') register_push(phone_type, registration_id, user) return Response(data)
class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' fields = ('id', 'name', 'area_of_interest', 'area_of_interest_name', 'scenarios', 'model_package', 'created_at', 'modified_at', 'is_private', 'is_activity', 'gis_data', 'mapshed_job_uuid', 'subbasin_mapshed_job_uuid', 'wkaoi', 'user', 'hydroshare', 'in_drb') user = UserSerializer(default=serializers.CurrentUserDefault()) gis_data = JsonField(required=False, allow_null=True) mapshed_job_uuid = serializers.SlugRelatedField( slug_field='uuid', queryset=Job.objects.all(), required=False, allow_null=True) subbasin_mapshed_job_uuid = serializers.SlugRelatedField( slug_field='uuid', queryset=Job.objects.all(), required=False, allow_null=True) scenarios = ScenarioSerializer(many=True, read_only=True) hydroshare = HydroShareResourceSerializer(read_only=True)
class CommentSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) review = ReviewSerializer(read_only=True) class Meta: model = Comment fields = ['id', 'text_content', 'author', 'review']
class SystemSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) class Meta: model = SystemModel fields = '__all__' def validate(self, data): if 'view' in self.context: project_id = self.context['view'].kwargs['project_id'] try: data['project'] = ProjectModel.objects.get(id=project_id) except ProjectModel.DoesNotExist: raise serializers.ValidationError("Invalid Project") return data def create(self, validated_data): if 'request' in self.context: validated_data['author'] = self.context['request'].user return SystemModel.objects.create(**validated_data) def update(self, instance, validated_data): for key in validated_data: default = getattr(instance, key) setattr(instance, key, validated_data.get(key, default)) instance.save() return instance
class RouteSerializer(serializers.ModelSerializer): transport = TransportSerializer(read_only=True) transport_id = serializers.IntegerField(write_only=True, required=False) owner = UserSerializer(read_only=True) start_point = CitySerializer(read_only=True) end_point = CitySerializer(read_only=True) start_point_id = serializers.IntegerField(write_only=True) end_point_id = serializers.IntegerField(write_only=True, allow_null=True) class Meta: model = Route fields = ROUTE_FIELDS read_only_fields = ('price', ) def validate(self, attrs): attrs['owner'] = self.context['request'].user transport_id = attrs.get('transport_id', -1) if transport_id is not -1: try: transport = Transport.objects.get(pk=transport_id) if transport.owner != attrs['owner']: raise serializers.ValidationError( {'transport_id': ["it is not your transport"]}) except Transport.DoesNotExist: raise serializers.ValidationError( {'transport_id': ["doesn't exist"]}) else: transport = None attrs['transport'] = transport return attrs
class CartSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) products = ProductSerializer(read_only=True) class Meta: model = Cart fields = ['user', 'products', 'created']
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, _ = Token.objects.get_or_create(user=user) return Response(UserSerializer(user).data)
class HistSerializer(ModelSerializer): firmware_set = FirmwareSerializer() user = UserSerializer() chipset = ChipsetSerializer() class Meta: model = HistVersion fields = ('id', 'chipset', 'firmware_set', 'infolink', 'date', 'user')
class ProjectSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' user = UserSerializer(default=serializers.CurrentUserDefault()) scenarios = ScenarioSerializer(many=True, read_only=True)
class ProjectUpdateSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' user = UserSerializer(default=serializers.CurrentUserDefault(), read_only=True)
def to_dict(self): return { 'room': self.room, 'user': UserSerializer(self.user).data, 'created': self.created, 'message': self.message, 'status': self.status, 'tags': self.tags }
class ProjectUpdateSerializer(serializers.ModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' fields = ('id', 'name', 'area_of_interest', 'area_of_interest_name', 'model_package', 'created_at', 'modified_at', 'is_private', 'is_activity', 'gis_data', 'mapshed_job_uuid', 'subbasin_mapshed_job_uuid', 'wkaoi', 'user', 'layer_overrides') user = UserSerializer(default=serializers.CurrentUserDefault(), read_only=True) gis_data = JsonField(required=False, allow_null=True) mapshed_job_uuid = serializers.SlugRelatedField( slug_field='uuid', queryset=Job.objects.all(), required=False, allow_null=True) subbasin_mapshed_job_uuid = serializers.SlugRelatedField( slug_field='uuid', queryset=Job.objects.all(), required=False, allow_null=True) def create(self, validated_data): """ Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886 From https://github.com/lock8/django-rest-framework-jwt-refresh-token/pull/35/files#diff-84229b1d4af72d928beddfa32e80cc8eR23 # NOQA via https://github.com/encode/django-rest-framework/issues/6031#issuecomment-398242587 # NOQA """ if 'user' not in validated_data: validated_data['user'] = self.context['request'].user return super(ProjectUpdateSerializer, self).create(validated_data) def validate(self, data): """ Ensure that all non-activity projects have a legitimate AoI. """ is_activity = data.get('is_activity', False) if not is_activity: try: # Validate that either AoI or WKAoI is specified correctly serializer = AoiSerializer(data=data) serializer.is_valid(raise_exception=True) except Exception: rollbar.report_exc_info() raise return data
class ProjectUpdateSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' user = UserSerializer(default=serializers.CurrentUserDefault(), read_only=True) gis_data = JsonField(required=False, allow_null=True)
def get(self, request): ''' 获取所有的User列表(actived的用户) :param request: :return: ''' users_actived = User.objects.filter(is_active=True) json_data = UserSerializer(users_actived, many=True).data return Response(json_data)
class ProjectSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Project depth = 1 geo_field = 'area_of_interest' user = UserSerializer(default=serializers.CurrentUserDefault()) gis_data = JsonField(required=False, allow_null=True) scenarios = ScenarioSerializer(many=True, read_only=True) hydroshare = HydroShareResourceSerializer(read_only=True)
def awaiters(self, request, pk): """ # 대기자 명단 * {id}에는 channel의 id를 넣으면 됨 * 해당 (비공개)채널에 구독을 신청한 대기자들의 목록 """ channel = self.get_object() awaiters = channel.awaiters serializer = UserSerializer(awaiters, partial=True, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
class ReviewSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) restaurant = RestaurantSerializer(read_only=True) likes_counter = serializers.SerializerMethodField() def get_likes_counter(self, restaurant): return restaurant.likes.all().count() class Meta: model = Review fields = '__all__'
def get(self, request, slug): user_name = request.GET.get('username') if user_name: user = User.objects.exclude(slug=slug).filter(user_name__icontains=user_name) else: user = User.objects.exclude(slug=slug) serialized_user = UserSerializer(user, many=True) try: result = serialized_user.data except: result_list = list(user.values('user_name', 'image', 'slug')) for item in result_list: item['image'] = '/media/' + item['image'] return HttpResponse(json.dumps(result_list)) return JsonResponse(result, safe=False)
class TransportSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) type = TransportTypeSerializer(read_only=True) type_id = serializers.IntegerField(write_only=True) mark_name = serializers.ReadOnlyField(source='model.mark.name') model_name = serializers.ReadOnlyField(source='model.name') load_type_name = serializers.ReadOnlyField(source='load_type.name') def create(self, validated_data): validated_data['owner'] = self.context['request'].user return super().create(validated_data) class Meta: model = Transport fields = TRANSPORT_FIELDS
def AuthLogin(request): userJSON = request.data['body'] user, created = User.objects.get_or_create( uid=userJSON['uid'], photoURL=userJSON['photoURL'], providerID=userJSON['providerId'], displayName=userJSON['displayName'], email=userJSON['email'], phoneNumber=userJSON['phoneNumber']) user.set_password('Informatica') user.save() authenticate(username=user.displayName, password='******') responseJSON = UserSerializer(user) return Response({'uid': userJSON['uid']}, status='200')
def get(self, *args, **kwargs): token = self.request.query_params.get('token') try: token = RefreshToken(token) user_id = token.payload.get('user_id') token.blacklist() except TokenError: return Response({"error": str(TokenError)}, status.HTTP_400_BAD_REQUEST) user = get_object_or_404(UserModel, pk=user_id) if not user.is_active: user.is_active = True user.save() from apps.user.serializers import UserSerializer serializer = UserSerializer(user) return Response(serializer.data, status.HTTP_200_OK)
class RestaurantSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) reviews_counter = serializers.SerializerMethodField() # average_rating = serializers.SerializerMethodField() # # def get_average_rating(self, restaurant): # number_of_ratings = restaurant.fk_review_restaurant.all().count() # total_of_stars = restaurant.fk_review_restaurant.rating.all() def get_reviews_counter(self, restaurant): return restaurant.fk_review_restaurant.all().count() class Meta: model = Restaurant fields = '__all__'