class ContratoSerializer(serializers.ModelSerializer): Cliente = UserSerializer(read_only=True) Gerente = UserSerializer(read_only=True) Menu = ContratoMenuSerializer(read_only=True) Montaje = MontajeSerializer(read_only=True) Restaurante = RestauranteSerializer(read_only=True) Salon = SalonSerializer(read_only=True) class Meta: model = Contrato fields = ('id', 'Cliente', 'Gerente', 'Menu', 'Montaje', 'Restaurante', 'Salon')
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = User.object.create_user(serializer.data['username'], serializer.data['email'], serializer.data['password']) refresh = RefreshToken.for_user(user=user) return JsonResponse( { 'refresh': str(refresh), 'access': str(refresh.access_token) }, status=201) return JsonResponse(serializer.errors, status=400)
def get(self, request, user_id): user = User.object.filter(user_id=user_id).first() if user: serial = UserSerializer(user) if serial: return JsonResponse(serial.data, status=200) return JsonResponse({'msg': 'No such user'}, status=404)
def user_list(request, format=None): if User.userAuth(request, tokkening=True) == False: print u"Access denied" return render_to_response('denied.html', context_instance=RequestContext(request)) if request.method == 'GET': users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) elif 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, instance, validated_data): user_data = validated_data.get('user') user_serializer = UserSerializer( data=user_data, partial=True ) # Parcial=True, para evitarnos la validacion de los campos que son requeridos ya que podriamos solo querer actualizar ciertos campos de la instancia if user_serializer.is_valid(raise_exception=True): user_instance = user_serializer.update( instance=instance.user, validated_data=user_serializer.validated_data) validated_data['user'] = user_instance instance.user = validated_data.get('user', instance.user) instance.gas_company = validated_data.get('gas_company', instance.gas_company) instance.save() return instance
class CommentUserSerializer(serializers.ModelSerializer): comment_owner = UserSerializer() class Meta: model = Comment fields = '__all__' read_only_fields = ['comment_owner']
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) })
class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() total_likes = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' read_only_fields = ['owner'] def get_total_likes(self, post): return post.like_by.count()
def user_detail(request, pk, format=None): if User.userAuth(request, tokkening=True) == False: print u"Access denied" return Response(status=status.HTTP_403_FORBIDDEN) try: user = User.objects.get(id=pk) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': 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) elif request.method == 'DELETE': user.delete() return Response(status=status.HTTP_204_NO_CONTENT)
class TrainingListSerializer(serializers.ModelSerializer): """ Списковый сериализатор тренировок """ user = UserSerializer(read_only=True) date = serializers.DateTimeField(required=False) class Meta: model = Training fields = [ 'id', 'date', 'user', ] def create(self, validated_data): return Training.objects.create(user=self.context['request'].user, **validated_data)
def emailcheck(self, request, pk=None): api_result = User.objects.filter(email=pk).order_by('-id') serializer_class = UserSerializer(api_result) return Response(serializer_class.data)
class CommentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Comment fields = ('id', 'text', 'food', 'user', 'date')
def retrieve(self, request): return Response(UserSerializer(request.user).data)
def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data)
class UserCompanyWriteSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) gas_company = serializers.PrimaryKeyRelatedField( required=False, queryset=GasCompany.objects.all()) type_user = serializers.CharField(max_length=3, write_only=True) class Meta: model = GasCompanyUser fields = ['id', 'user', 'gas_company', 'type_user'] def create(self, validated_data): _user = self.context['user'] try: gas_station_admin = GasCompanyUser.objects.get(user=_user) gas_station = gas_station_admin.gas_company validated_data.update(gas_company=gas_station) except GasCompanyUser.DoesNotExist: try: validated_data['gas_company'] except KeyError: raise serializers.ValidationError( {"gas_company": "Este campo es Requerido"}) user_data = validated_data.pop('user') raw_password = user_data.pop('password') user_instance = User.objects.create(**user_data) user_instance.set_password(raw_password) user_instance.save() type_user = validated_data.pop('type_user') if type_user == '40C': # AdminGasCompany try: user_group = Group.objects.get(name='AdminGasCompany') except Group.DoesNotExist: raise serializers.ValidationError( 'El grupo AdminGasCompany No existe') user_group.user_set.add(user_instance) elif type_user == '20C': try: user_group = Group.objects.get(name='Employee') except Group.DoesNotExist: raise serializers.ValidationError( 'El grupo Employee No existe') user_group.user_set.add(user_instance) elif type_user == 'ED': try: user_group = Group.objects.get(name='Operator') except Group.DoesNotExist: raise serializers.ValidationError( 'El grupo Operator No existe') user_group.user_set.add(user_instance) validated_data.update(user=user_instance) g_user = GasCompanyUser.objects.create(**validated_data) return g_user def update(self, instance, validated_data): user_data = validated_data.get('user') user_serializer = UserSerializer( data=user_data, partial=True ) # Parcial=True, para evitarnos la validacion de los campos que son requeridos ya que podriamos solo querer actualizar ciertos campos de la instancia if user_serializer.is_valid(raise_exception=True): user_instance = user_serializer.update( instance=instance.user, validated_data=user_serializer.validated_data) validated_data['user'] = user_instance instance.user = validated_data.get('user', instance.user) instance.gas_company = validated_data.get('gas_company', instance.gas_company) instance.save() return instance
def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data)
def update(self, request, pk=None): user = User.objects.get(username=self.request.user) for key in request.data.keys(): setattr(user, key, request.data[key]) user.save() return Response(UserSerializer(user).data)