class FriendSerializer(serializers.ModelSerializer): requester = UserSerializer() receiver = UserSerializer() class Meta: model = Friend fields = ['id', 'requester', 'receiver', 'status', 'created']
class FriendSerializer(serializers.ModelSerializer): requester = UserSerializer(read_only=True) receiver = UserSerializer(read_only=True) class Meta: model = FriendRequest fields = '__all__'
def create(self, request, *args, **kwargs): try: request.data['username'] = request.data.get('email') user_serializer = UserSerializer(data=request.data, partial=False) if user_serializer.is_valid(): user_serializer.save() email = request.data['email'] last_user = User.objects.get(email=email) activation_code = random_string() code_data = { 'requester_id': last_user.id, 'type': 'registration', 'code': activation_code, 'expiry': datetime.now(tz=timezone.utc) + timedelta(days=1) } code_serializer = CodeSerializer(data=code_data) if code_serializer.is_valid(): code_serializer.save() send_luna_emails(last_user, 'activation', activation_code) return Response(None, status=status.HTTP_204_NO_CONTENT) else: return Response(code_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) except AttributeError as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST)
def get(self,request,user_id=None): if(user_id): userprofile = UserProfile.objects.get(pk=user_id) user_data = UserSerializer(userprofile) else: userData = UserProfile.objects.all() user_data = UserSerializer(userData, many=True) return Response(user_data.data)
def run_github_aggregator(cls, location): for user in cls.get_github_users_by_location(location=location): ElasticSearchIndexerServices.index_user_in_elasticsearch( user_id=user.user_id, user_serializer_data=UserSerializer(user).data) celery.send_task("index_user_contributions", [ user.user_id, user.user_profile_page, UserSerializer(user).data ])
def put(self,request,user_id): try: get_data = UserProfile.objects.get(pk=user_id) update_data = UserSerializer(get_data,data=request.data) if update_data.is_valid(): update_data.save() return Response(update_data.data) except: return Response("Error" ,status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, *args, **kwargs): request.data['username'] = request.data.get('email') serializer = UserSerializer(request.user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(None, status=status.HTTP_204_NO_CONTENT) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_user_serializer(self): user = create_user_mock() user_serializer = UserSerializer(user=user) user_dict = user_serializer.to_representation() self.assertIn('user_id', user_dict) self.assertIn('username', user_dict) self.assertIn('location', user_dict) self.assertIn('contributions', user_dict) self.assertEqual(user_dict['user_id'], USER_ID_MOCK) self.assertEqual(user_dict['username'], USERNAME_MOCK) self.assertEqual(user_dict['location'], LOCATION_MOCK) self.assertEqual(user_dict['contributions'], CONTRIBUTIONS_MOCK)
class PostSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Post fields = '__all__' read_only_fields = ['user']
class PostSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) images = ImageSerializer(many=True, required=False) logged_in_user_liked = serializers.SerializerMethodField() is_from_logged_in_user = serializers.SerializerMethodField() amount_of_likes = serializers.SerializerMethodField() shared = SharedPostSerializer(required=False) def get_logged_in_user_liked(self, post): user = self.context['request'].user if post in user.liked_posts.all(): return True return False def get_is_from_logged_in_user(self, post): user = self.context['request'].user if user == post.user: return True return False @staticmethod def get_amount_of_likes(post): return post.liked_by.all().count() class Meta: model = Post fields = '__all__' def create(self, validated_data): validated_data['user'] = self.context['request'].user post = super().create(validated_data=validated_data) return post
def get(self,request): project_Data= Projects.objects.all() project_data = ProjectSerializer(project_Data,many=True) # print(project_data.data) project_dict={"projectlist":project_data.data} userData = UserProfile.objects.all() user_data = UserSerializer(userData, many=True) # print(user_data.data) user_dict={"userslist":user_data.data} user_dict.update(project_dict) print(user_dict) return render(request,'assignproject.html',user_dict) # def user_page(request, username): # try: # user = User.objects.get(username=username) # except: # raise Http404('Requested user not found.') # template = get_template('assignproject.html') # variables = Context({ # 'username': username, # }) # output = template.render(variables) # return HttpResponse(output)
def post(self, request): """ This api make user login. url: user/login """ try: if request.data.get('email') and request.data.get('password'): user = UserSerializer(data=request.data) if not user.is_valid(): return ApiResponse().error(user.errors, 400) try: user_email = User.objects.get( email=request.data.get('email')) auth_user = authenticate( username=user_email, password=request.data.get('password')) except Exception as err: print(err) return ApiResponse().error("Invalid username or password", 400) if not auth_user: return ApiResponse().error("invalid username or password", 400) token, create = Token.objects.get_or_create( user_id=auth_user.id) if (auth_user): try: userprofile = UserProfile.objects.get( user_id=auth_user.id, is_deleted=False) user_data = ProfileSerializer(userprofile) except Exception as err: print(err) return ApiResponse().error("invalid email or password", 400) token_value = { 'token': token.key, } user_response = user_data.data user_response.update(token_value) return ApiResponse().success(user_response, 200) return ApiResponse().error( "Please send correct email and password", 400) except Exception as err: print(err) return ApiResponse().error("Error while login", 500)
def post(self,request): try: user = self.create_user(request) if not(user): return Response("Error while create user",status=status.HTTP_404_NOT_FOUND) self.overWrite(request, {'user':user.id}) print(request.data) user_data = UserSerializer(data=request.data) if not(user_data.is_valid()): return Response(user_data.errors,status=status.HTTP_404_NOT_FOUND) user_data.save() return Response(user_data.data,status=status.HTTP_201_CREATED) except Exception as err: print(err) return Response("Error",status=status.HTTP_404_NOT_FOUND)
class ProjectsSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source="created_by.username") shared_with = UserSerializer(many=True, required=False) tasks = TasksSerializer(many=True, required=False) class Meta: fields = "__all__" model = Project
class PostSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) amount_of_likes = serializers.SerializerMethodField() @staticmethod def get_amount_of_likes(self, post): return post.likes.all().count() class Meta: model = Post fields = "__all__"
def post(self,request,*args, **kwargs): ## written by aarti ## try: # get_value= request.body # print(get_value) userlist =[] email = request.POST.get('inputEmail') password = request.POST.get('inputPassword') print(email) print(password) if email: user = User.objects.get(username=email) auth_user = authenticate(username=email, password=password) print(auth_user) # login(request, user) token,created = Token.objects.get_or_create(user_id=user.id) print(token) if(user): userprofile = UserProfile.objects.get(user_id=user.id) user_data = UserSerializer(userprofile) else: userData = UserProfile.objects.all() user_data = UserSerializer(userData,many=True) token_value = { 'token':token.key, } user_response = user_data.data user_response.update(token_value) print(user_response) return JsonResponse(user_response) # else: # return JsonResponse({'status':'404'}) # return render(request,'dashboard.html') except Exception as e: print(e) return JsonResponse({'Error':'err'})
class CommentSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) is_from_logged_in_user = SerializerMethodField() def get_is_from_logged_in_user(self, comment): user = self.context['request'].user if user == comment.user: return True return False class Meta: model = Comment fields = '__all__'
def post(self, request): """ This api create user.'Email' and 'Password' field is required. url: user/create """ try: user_info = UserSerializer(data=request.data) if not user_info.is_valid(): return ApiResponse().error(user_info.errors, 400) user = self.create_user(request) if not (user): return ApiResponse().error("This email is already exists", 400) RequestOverwrite().overWrite(request, {'user': user.id}) user_data = ProfileSerializer(data=request.data) if not (user_data.is_valid()): return ApiResponse().error(user_data.errors, 400) user_data.save() return ApiResponse().success(user_data.data, 200) except Exception as err: print(err) return ApiResponse().error( "There is a problem while creating user", 500)
def post(self, request, *args, **kwargs): try: code_entry = ActivationCodes.objects.get( code=self.kwargs.get('code')) user = User.objects.get(id=code_entry.requester_id_id) if code_entry.expiry > datetime.now(tz=timezone.utc): user_serializer = UserSerializer(user, data={'is_active': True}, partial=True) if user_serializer.is_valid(): user_serializer.save() return Response(None, status=status.HTTP_204_NO_CONTENT) return Response('Input validation error', status=status.HTTP_400_BAD_REQUEST) else: return Response('Activation code has expired', status=status.HTTP_422_UNPROCESSABLE_ENTITY) except User.DoesNotExist as e: return Response(str(e), status=status.HTTP_404_NOT_FOUND) except ActivationCodes.DoesNotExist as e: return Response(str(e), status=status.HTTP_404_NOT_FOUND)
def put(self, request, *args, **kwargs): serializer_data = request.data.get('user', {}) serializer = UserSerializer(request.user, data=serializer_data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) user = User.objects.get(email=request.data['email']) req = request req.user = user user_serializer = UserSerializer(instance=user, context={'request': req}) res = {'user': user_serializer.data, **serializer.validated_data} return Response(res, status=status.HTTP_200_OK)
def post(self, *args, **kwargs): type = self.request.data.get('type').lower() search_string = self.request.query_params.get('search') if type == 'restaurant': return Response( RestaurantSerializer( Restaurant.objects.filter(name__icontains=search_string), many=True).data) elif type == 'user': return Response( UserSerializer( User.objects.filter(username__icontains=search_string), many=True).data) elif type == 'review': return Response( ReviewSerializer(RestaurantReview.objects.filter( text_content__icontains=search_string), many=True).data) else: return Response('Nothing')
class RestaurantSerializer(serializers.ModelSerializer): author = UserSerializer(required=False, read_only=True) # show the details of the author average_rating = serializers.SerializerMethodField() def get_average_rating(self, instance): # average = RestaurantReview.objects.filter(restaurant_reviewed=instance).aggregate(rating=Avg('rating')) average = Restaurant.objects.filter(id=instance.id).aggregate( rating=Avg('reviews__rating')) if average is None: return 0 return average class Meta: model = Restaurant fields = [ 'id', 'name', 'category', 'street', 'city', 'zip', 'website', 'phone', 'email', 'opening_hours', 'price_level', 'author', 'average_rating', 'image' ] read_only_fields = ['author']
def get(self,request): userData = UserProfile.objects.all() user_data = UserSerializer(userData, many=True) print(user_data.data) data={"uname":user_data.data} return render(request,'user.html',data)
def build_user_document(cls, github_user): user = cls.create_user_from_github_user_class(github_user=github_user) return ElasticSearchIndexerServices.make_index_document( user_id=user.user_id, user_serializer_data=UserSerializer(user).data)
def get(self, request, *args, **kwargs): user = User.objects.get(id=self.request.user.id) serializer = UserSerializer(instance=user, many=False) return Response(data=serializer.data)
def post(self, request): user = request.data serializer = UserSerializer(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
class ReviewSerializer(serializers.ModelSerializer): review_owner = UserSerializer(read_only=True) class Meta: model = RestaurantReview fields = ['id', 'restaurant_reviewed', 'content', 'review_owner', 'created', 'rating']
class SharedPostSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Post fields = '__all__'