class UnreadMessageSerializer(serializers.ModelSerializer): user_from = UserSerializer(read_only=True) user_to = UserSerializer(read_only=True) store = StoreSerializer(read_only=True) class Meta: model = Message fields = ['user_from', 'user_to', 'store', 'content', 'created']
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED)
def put(self, request, *args, **kwargs): #可以执行条件 #首先判断用户名是否 upk = kwargs['pk'] password = make_password(request.data['password']) aimdata = copy.deepcopy(request.data) print(aimdata) aimdata['password']=password print(aimdata) oldobj = User.objects.get(pk=upk) userserializer = UserSerializer(oldobj,data=aimdata,partial=True) if userserializer.is_valid(): userserializer.save() #如果创建成功,返回对应id的对应url returndata = { "desc":"user add", "data":{ "upk": upk }, "code":200, "error":0, "detail":"add success" } return Response(returndata,status=status.HTTP_200_OK)
def put(self, request, pk, format=None): obj = User.objects.get(id=pk) serializer = UserSerializer(obj, data=request.data) if serializer.is_valid(): serializer.save() return update(serializer) return failure(serializer)
class ParticipationSerializer(serializers.ModelSerializer): member = UserSerializer(many=True, read_only=True) leader = UserSerializer(read_only=True) class Meta: model = ChallengesParticipation fields = '__all__'
def pre_save(self, obj): user_data = self.request.DATA.get('user', {}) thumbnail_image = self.request.DATA.get('thumbnail_image_obj', {}) main_image = self.request.DATA.get('main_image_obj', {}) full_name = user_data.get('full_name', '').split(' ') user_data['first_name'] = full_name[0] if thumbnail_image: obj.thumbnail_image.save( thumbnail_image['name'], ContentFile(thumbnail_image['file'].decode('base64')), save=False) if main_image: obj.main_image.save(main_image['name'], ContentFile( main_image['file'].decode('base64')), save=False) if len(full_name) > 1: user_data['last_name'] = ' '.join(full_name[1:]) user_serializer = UserSerializer(obj.user, data=user_data) if user_serializer.is_valid(): password = user_data.get('password_1', '') if password: if password == user_data.get('password_2', ''): user_serializer.object.set_password(password) user_serializer.save()
class UserBlocksSerializers(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) blocks = UserSerializer(many=False, read_only=True) class Meta: model = UserBlocks fields = ['id', 'user', 'blocks', 'created_at', 'updated_at']
class ChatSessionSerializers(serializers.ModelSerializer): creator = UserSerializer(many=False, read_only=True) invited_user = UserSerializer(many=False, read_only=True) class Meta: model = ChatSession fields = ['id', 'uri', 'creator', 'invited_user']
def post(self, request): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response( 'Пользователь успешно зарегистрирован. Подтвердите аккаунт по почте', status=201)
class TicketSerializer(serializers.ModelSerializer): collection = TicketCollectionMiniSerializer() assigned_by = UserSerializer() assigned_to = UserSerializer() class Meta: model = Ticket fields = '__all__'
def patch(self, request, username): user = self.get_object(username) serializer = UserSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) teacher = Teacher.objects.create(user=user, bio=validated_data.pop('bio')) teacher.save() return teacher
def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) student = Student.objects.create(user=user, bio=validated_data.pop('bio')) student.save() return student
class TicketSerializer(serializers.ModelSerializer): """Class to handle the serializing and deserializing of ticket data""" creator = UserSerializer(read_only=True) assigned_to = UserSerializer(read_only=True) class Meta: """Class to add additional information to the serializer""" model = Ticket fields = '__all__'
class FriendshipRequestSerializers(serializers.ModelSerializer): from_user = UserSerializer(many=False, read_only=True) to_user = UserSerializer(many=False, read_only=True) class Meta: model = FriendshipRequest fields = [ 'id', 'from_user', 'to_user', 'message', 'accepted', 'created_at', 'updated_at' ]
def put(self, request, pk, format=None): try: user = get_object_or_404(User, pk) print(user) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) except Http404 as e: message = {"message": "User does not exist"} return JsonResponse(message, status=404)
def post(self, request, format=None): """ Register a user account """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): User.objects.create_user( username=serializer.data.get('username'), email=serializer.data.get('email'), password=serializer.data.get('password'), first_name=serializer.data.get('first_name'), last_name=serializer.data.get('last_name')) return Response(status.HTTP_200_OK) else: return Response(status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) bucket = request.data['bucket'] tenants = User.objects.filter(bucket=bucket) if len(tenants) >= 5: message = {'message': 'Select another bucket'} return JsonResponse(message, status=400) if serializer.is_valid(): serializer.validated_data serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
class ArticleSerializers(serializers.ModelSerializer): class Meta: model = Article fields = [ 'article_id', 'title', 'main_data', 'line', 'author', 'written_on', 'search_tag', ] read_only_fields = [ 'article_id', 'title', 'line', 'main_data', 'author', 'written_on', 'search_tag', ] author = UserSerializer() search_tag = serializers.SlugRelatedField( many=True, slug_field='search_tag', read_only=True, )
def jwt_response_payload_handler(token, user=None, request=None) -> dict: return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data, }
class PartyUserSerializer(serializers.ModelSerializer): party = PartySerializer() user = UserSerializer() class Meta: model = PartyUser fields = '__all__'
def get_blocked_users(self, request): blocked = BlockedUser.objects.filter(blocker=request.user) serialized_data = [] for u in blocked: serialized_data.append(UserSerializer(u.blocked).data) return Response(data={'blocked_users': serialized_data}, status=status.HTTP_200_OK)
class MovieSerializer(serializers.HyperlinkedModelSerializer): moviesimage_set = Movies_ImageSerializer(allow_null=True, many=True, read_only=True) user = UserSerializer(read_only=True) url = serializers.HyperlinkedRelatedField(view_name="api:movie-detail", read_only=True, lookup_field="user") class Meta: model = Movie fields = ['id','url', 'user', 'title', 'moviesimage_set', 'description', 'no_of_ratings', 'avg_rating'] def create(self, validated_data): print("another", self.context['included_images'] ) data = self.context['movie_info'] movie_title = data['title'] movie_description = data['description'] #movie_description = data['image'] currentUser = User.objects.get(id=self.context['request'].user.id) movie_obj = Movie.objects.get_or_create( title = movie_title, description = movie_description, user = currentUser ) images_data = self.context['included_images'] movie_instance = movie_obj[0] print('its instance movie', movie_instance) for i in images_data.getlist('image'): print("another", i) MoviesImage.objects.create(movie=movie_instance, image=i, user=self.context['request'].user) print('its done', movie_obj) return movie_instance
class ExpenseClaimSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: model = ExpenseClaim fields = ('name', 'description', 'status', 'user', 'id', 'photos') depth = 1
def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data }
def jwt_response_payload_handler(token, user=None, request=None) -> dict: return { "token": token, "user": UserSerializer(user, context={ "request": request }).data }
class TicketMiniSerializer(serializers.ModelSerializer): collection = TicketCollectionMiniSerializer() assigned_by = UserSerializer() class Meta: model = Ticket exclude = ('description', 'created', 'parent', 'assigned_to')
class SongSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) party = PartySerializer(read_only=True) likes = serializers.SerializerMethodField(read_only=True) like = serializers.SerializerMethodField(read_only=True) class Meta: model = Song fields = ( 'id', 'user', 'party', 'player', 'source', 'name', 'date', 'likes', 'like', ) def get_likes(self, obj): return Like.objects.filter(kind=Like.Kind.SONG, like=obj.pk).count() def get_like(self, obj) -> int: return get_serializer_like(self, obj, Like.Kind.SONG)
class ShopUserSerializers(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) shop = ShopSerializers(many=False, read_only=True) class Meta: model = ShopUser fields = ['user', 'id', 'shop']
def user_list(request): try: users = User.objects.all() except User.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUD) serializer = UserSerializer(users, many = True) return Response(serializer.data)