def put(self, request, username, format=None): user = request.user userdata = self.getUser(username=username) if userdata is None: return Response(status=status.HTTP_404_NOT_FOUND) elif userdata.username != user.username: return Response(status=status.HTTP_401_UNAUTHORIZED) else: user = UserProfile.objects.get(user=userdata) serializer = UserProfileSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_404_NOT_FOUND) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ListDossierSerializer(serializers.ModelSerializer): owner = UserProfileSerializer('owner', read_only=True) shared_users = UserProfileSerializer('shared_users', many=True, read_only=True) class Meta: model = Dossier fields = ('id', 'title', 'accessibility', 'color', 'created_at', 'last_modified', 'is_verified', 'ordering_id', 'owner', 'shared_users') read_only_fields = ('is_verified', 'ordering_id')
def get_weather(cls, ip): url = "http://restapi.amap.com/v3/weather/weatherInfo?" adcode = cls.get_adcode_from_ip(ip) parameters = "key=%s&adcode=%s" % (cls.key, adcode) url += parameters users = UserProfileSerializer(UserProfile.objects.all(), many=True).data user = UserProfileSerializer(user.profile).data print users, user
class EducatorSerializer(serializers.ModelSerializer): """Educator model serializer.""" id = UserProfileSerializer(required=False) class Meta: model = Educator fields = '__all__'
class ListMyCouponsSerializer(serializers.ModelSerializer): coupon = DetailCouponSerializer(read_only=True) user = UserProfileSerializer(read_only=True) class Meta: model = CouponUser fields = ['id', 'created_at', 'user', 'coupon', 'qr_code', 'used']
def user_api_login(request): """用户登陆接口""" # 1.获取用户输入信息 if request.method == 'POST': # 2.表单验证 form = LoginForm(data=request.POST) print(form) # 3.如果表单验证通过,执行登陆 if form.is_valid(): user = form.do_login(request) profile = user.profile # 4.返回用户的基本信息和详细信息 data = { 'user': UserSerializer(user).to_dict(), 'profile': UserProfileSerializer(profile).to_dict() } return http.JsonResponse(data) # 5.如果表单验证不通过,返回用户登陆的错误信息 else: err = json.loads(form.errors.as_json()) return BadJsonResponse(err) # 6.如果当前的请求不是post而是get 则返回获取方式错误的信息 else: return MethodNotAllowResponse()
def validate(self, attrs): username = attrs.get("username") password = attrs.get("password") result, token = KMITLBackend.authenticate(username, password) if result == KMITLBackend.Status.ALREADY_EXISTS: if token: user = token.user if user.is_active: user_profile = UserProfile.objects.get(user=user) user.last_login = timezone.now() user.save() serializer = UserProfileSerializer(user_profile) data = serializer.data data["result"] = result data["token"] = str(token) return data else: raise serializers.ValidationError( "This account has been suspended. Please contact our staff for more detail." ) elif result == KMITLBackend.Status.FIRST_TIME: return {"result": result, "username": username} else: raise serializers.ValidationError( "The username or password is incorrect.")
def to_representation(self, instance): user_history = super(CurrentUsedBikeSerializer, self).to_representation(instance) user_id = user_history.pop("user") user = UserProfile.objects.get(user_id=user_id) user_serializer = UserProfileSerializer(user) user_history["user"] = user_serializer.data user_history["bike"].pop("latitude") user_history["bike"].pop("longitude") selected_plan_id = user_history.pop("selected_plan") selected_plan = BikeUsagePlan.objects.get(id=selected_plan_id) plan_serializer = BikeUsagePlanSerializer(selected_plan) user_history["selected_plan"] = plan_serializer.data user_history["timestamps"] = {} user_history["timestamps"]["borrow_date"] = str(instance.borrow_time.date().strftime("%B %d, %Y")) user_history["timestamps"]["borrow_time"] = str(timezone.localtime(instance.borrow_time).strftime("%I:%M %p")) if instance.return_time is None: duration = calculate_duration(instance.borrow_time, timezone.now()) else: user_history["timestamps"]["return_date"] = str(instance.return_time.date().strftime("%B %d, %Y")) user_history["timestamps"]["return_time"] = str(timezone.localtime(instance.return_time).strftime("%I:%M %p")) duration = calculate_duration(instance.borrow_time, instance.return_time) distance = calculate_distance(instance.route_line) user_history["duration"] = duration user_history["distance"] = distance route_line = user_history.pop("route_line") #user_history["route_line"] = json.loads(route_line) route = json.loads(route_line) user_history["route_line"] = route[len(route)-1] return user_history
class StudentSerializer(serializers.ModelSerializer): """Student model serializer.""" id = UserProfileSerializer(required=False) educators = EducatorSerializer(required=False, many=True) categories = CategorySerializer(required=False, many=True) class Meta: model = Student fields = '__all__'
class ReviewDetailSerializer(serializers.ModelSerializer): user = UserProfileSerializer() replyset = ReplySerializer(many=True, source='reply_set') class Meta: model = Review fields = [ 'id', 'content', 'storeid', 'userid', 'score', 'reg_time', 'created_at', 'user', 'replyset' ]
def get(self, request, user_id): if int(user_id) is request.user.id: serializer = self.get_serializer(data=request.data) if serializer.is_valid(): instance = self.get_object(request) user_profile_serializer = UserProfileSerializer(instance) return Response(user_profile_serializer.data, status=HTTP_200_OK) error_message = self.get_error_message(serializer.errors) return Response({"detail": error_message}, status=HTTP_400_BAD_REQUEST) raise AuthenticationFailed()
def get(self, request, format=None): try: user_List = UserProfile.objects.all() serializer = UserProfileSerializer(user_List, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND)
def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) user = User.objects.get(id=self.user.id) user_serializer = UserProfileSerializer(instance=user, many=False) data['user'] = user_serializer.data return data
class DossierSerializer(serializers.ModelSerializer): content = serializers.SerializerMethodField() owner = UserProfileSerializer('owner', read_only=True) shared_users = UserProfileSerializer('shared_users', many=True, read_only=True) # So what we do here is we add in extra items into the CONTENT array # Where those extra items are actually files and made up of a different model # than the actual content array is made of # BUT it gonna have the same fields so that the front-end part would work the same/similarly @staticmethod def get_content(item): files_queryset = File.objects.filter(dossier_id=item.pk) files_serializer = FilesSerializer(files_queryset, many=True, read_only=True).data content_queryset = Content.objects.filter(dossier_id=item.pk) content_serializer = ContentDetailSerializer(content_queryset, many=True, read_only=True).data result_list = list(chain(files_serializer, content_serializer)) return result_list class Meta: model = Dossier fields = ('id', 'title', 'accessibility', 'color', 'created_at', 'last_modified', 'is_verified', 'ordering_id', 'owner', 'shared_users', 'content') read_only_fields = ('is_verified', 'ordering_id')
def get(self, request, username, format=None): userdata = self.getUser(username=username) if userdata is None: return Response(status=status.HTTP_404_NOT_FOUND) user = UserProfile.objects.get(user=userdata) serializer = UserProfileSerializer(user) print(serializer.data) return Response(data=serializer.data, status=status.HTTP_200_OK)
def get(self, request): # 获取用户 user = request.user # 用户是否未游客 if not user.is_authenticated: # 返回401状态码,表示用户未登陆 return UnauthorizedJsonResponse() else: profile = user.profile # 4.返回用户的基本信息和详细信息 data = { 'user': UserSerializer(user).to_dict(), 'profile': UserProfileSerializer(profile).to_dict() } return http.JsonResponse(data)
def validate(self, attrs): try: gender = attrs.pop("gender") phone_no = attrs.pop("phone_no") username = attrs.pop("username") attrs["username"] = username.replace("@kmitl.ac.th", "") user = User.objects.create(**attrs) user_profile = UserProfile.objects.create(user=user, gender=gender, phone_no=phone_no) PointTransaction.objects.create(user=user, point=DEFAULT_POINTS, transaction_type=PointTransaction.Type.INITIAL) serializer = UserProfileSerializer(user_profile) return serializer.data except IntegrityError: raise serializers.ValidationError("The user already exists.") except (TypeError, ValueError): raise serializers.ValidationError("Enter a valid information.")
def validate(self, attrs): token = attrs.get("token") try: token, created = Token.objects.get_or_create(key=token) user = token.user user.last_login = timezone.now() user.save() user_profile = UserProfile.objects.get(user=user) user.last_login = timezone.now() user.save() serializer = UserProfileSerializer(user_profile) data = serializer.data data["token"] = str(token) return data except IntegrityError: raise serializers.ValidationError("The token is already expired.")
class QuerySerializer(serializers.ModelSerializer): shared_users = UserProfileSerializer('shared_users', many=True, read_only=True) class Meta: model = Query fields = ( 'id', 'owner', 'shared_users', 'title', 'filters', 'sort_by', 'page', 'tab', 'created_at', )
def usersThatSharedView(request, postId): try: post = Post.objects.get(pk=postId) except Post.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == 'GET': paginator = PageNumberPagination() paginator.page_size = 10 userProfileList = UserProfile.objects.filter(user__in=post.shared.all()) result_page = paginator.paginate_queryset(userProfileList, request) serializer = UserProfileSerializer(result_page, many=True, context={'request':request}) return paginator.get_paginated_response(serializer.data) return Response(status=status.HTTP_400_BAD_REQUEST)
class StorySerializer(serializers.ModelSerializer): author = UserProfileSerializer(required=False) class Meta: model = Story fields = '__all__' def create(self, validated_data): user = self.context['request'].user user_profile = UserProfile.objects.get(user=user) story, created = Story.objects.update_or_create( author=user_profile, title=validated_data['title'], content=validated_data['content'], ) if hasattr(validated_data, 'genre'): story.genre = validated_data['genre'] story.save() return story
def get_profile(self, obj): return UserProfileSerializer(obj.user_profile, read_only=True).data
def obj_userName(self, obj): user_profile = UserProfile.objects.get(user=obj.user) user_serializer = UserProfileSerializer(user_profile) return user_serializer.data
def get_profile(self, obj): user_profile = Profile.objects.get(user=obj.user) serializer = UserProfileSerializer(user_profile) return serializer.data
def test_picture_url(self): serial = UserProfileSerializer(instance=self.user) assert ('anon_user.png' in serial.data['picture_url'])
def get_user(self, instance, *args, **kwargs): return UserProfileSerializer(instance.user.profile, fields=('id', 'full_name', 'avatar',)).data
class ShareDossierSerializer(serializers.ModelSerializer): user = UserProfileSerializer(many=True) class Meta: model = Dossier fields = ('user',)