def put(request): contact = Contact.objects.get(id=request.data['id']) payload = request.data serializer = ContactSerializer(contact, data=payload, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=HTTP_200_OK)
def post(self, request): request.data['owner'] = request.user.id incoming = ContactSerializer(data=request.data) if not incoming.is_valid(raise_exception=True): return Response(incoming.errors, status=status.HTTP_400_BAD_REQUEST) new_contact = incoming.create(incoming.validated_data) outgoing = ContactSerializer(instance=new_contact) return Response(outgoing.data, status=status.HTTP_201_CREATED)
def put(self, request, pk): contact = self.my_get_object(pk) incoming = ContactSerializer(instance=contact, data=request.data, partial=True) if not incoming.is_valid(raise_exception=True): return Response(incoming.errors, status=status.HTTP_400_BAD_REQUEST) new_contact = incoming.save() outgoing = ContactSerializer(instance=new_contact) return Response(outgoing.data, status=status.HTTP_200_OK)
def dashboard(request): user_contacts = Contact.objects.order_by('-contact_date').filter( user_id=request.user.id) context = {'contacts': ContactSerializer(user_contacts, many=True).data} return JsonResponse(context)
def post(request): token = request.META.get('HTTP_AUTHORIZATION') token = token.split(" ")[1] _id = Token.objects.get(key=str(token)) data = { "first_name": request.data['first_name'], "last_name": request.data['last_name'], "note": request.data['note'], "dob": request.data['dob'], "user_id": _id.user_id } serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors)
def get(request): token = request.META.get('HTTP_AUTHORIZATION') token = token.split(" ")[1] pk = Token.objects.get(key=str(token)) user = User.objects.get(id=pk.user_id) contact = Contact.objects.filter(user_id=user.id) serializer = ContactSerializer(contact, many=True) return Response(serializer.data)
def create(self, request, format=None): serializer = ContactSerializer(data=request.data) contact = Contact(name=request.data['name'], phone_number=request.data['phone_number'], image='/images/what.png') contact.save() return redirect('/') return Response({'detail': 'Contact created'})
def test_retrieve_single_contact(self): # Test retrieving a contact request = factory.get('api/v1/contacts/', args=[self.contact_casper.id]) force_authenticate(request, user=self.user) contact_list = ContactsViewset.as_view({'get': 'retrieve'}) res = contact_list(request, pk=self.contact_casper.id) ingredients = Contact.objects.filter(user=self.user) serializer = ContactSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK)
def test_retrieve_contacts_list( self): # Test retrieving a list of contacts request = factory.get('api/v1/contacts/') force_authenticate(request, user=self.user) view = ContactsViewset.as_view({'get': 'list'}) res = view(request) ingredients = Contact.objects.filter(user=self.user) serializer = ContactSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK)
def list(self, request): if request.method == 'GET': user = get_user_model().objects.get(pk=request.user.pk) queryset = user.contacts.all() return Response( ContactSerializer(queryset, many=True, context={ 'request': request }).data)
def update_person(self, request, pk, format=None): print("cheese and crackers") queryset = Contact.objects.all.get(pk=pk) serializer = ContactSerializer(queryset, data=request.data) contact = Contact(name=request.data['name'], phone_number=request.data['phone_number'], image='/images/what.png') contact.save() return redirect('/') return Response({'detail': 'Contact edited'})
class UserInformationSerializer(serializers.ModelSerializer): """" get All User Info """ user = UserSerializer(read_only=True) contact = ContactSerializer(read_only=True) class Meta: model = UserInformation fields = ["user", "contact"]
class MessagesSerializer(serializers.ModelSerializer): """ Serializes each individual message """ to = ContactSerializer() class Meta: fields = '__all__' model = Message
def post(self, request, *args, **kwargs): data = request.data first_name = data.get('first_name') last_name = data.get('last_name') phone_number = data.get('phone_number') """ Check Json """ if not data: return Response({'error': 'Json not found'}, status=400) if not first_name: return Response({'error': 'First_name not found in json'}, status=400) if not last_name: return Response({'error': 'Last_name not found in json'}, status=400) if not phone_number: return Response({'error': 'Phone_number not found in json'}, status=400) user = get_user_model().objects.filter(pk=request.user.pk).first() if not user: return Response({'error': 'user not found in json'}, status=404) contactObj = Contact.objects.filter(phone_number=phone_number).first() if not contactObj: """ Create new contact """ contactSerializer = ContactSerializer(data=request.data) if contactSerializer.is_valid(): contactSerializer.save() else: """ Update contact """ contactSerializer = ContactSerializer(contactObj, data=request.data) if contactSerializer.is_valid(): contactSerializer.save() user.contacts.add(contactObj) user.save() return Response(status=201)
def search_by_phone_number(request): try: search_number = request.GET.get('mobile') contacts = Contact.objects.filter(mobile=search_number) if contacts.exclude(owner=None): contacts = contacts.exclude(owner=None) serializer = ContactSerializer(contacts, many=True) return Response({ 'status': 'success', 'data': serializer.data }, status=200) serializer = ContactSerializer(contacts, many=True) paginator = PageNumberPagination() paginator.page_size = 20 paginated_contacts = paginator.paginate_queryset(contacts, request) serializer = ContactSerializer(paginated_contacts, many=True) return paginator.get_paginated_response(serializer.data) except Exception as e: return Response({'status': 'error', 'message': str(e)}, status=400)
def test_get_a_contact(self): """ This test ensures that a single contact (with a given id) can be retrieved """ # Retrieve response from API response = self.fetch_contact(self.valid_contact_id) # Fetch data from database expected = Contact.objects.get(pk=self.valid_contact_id) serialized = ContactSerializer(expected) self.assertEqual(response.json(), serialized.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
class ReportOrderSerializer(serializers.ModelSerializer): sale_rep = MeSerializer() packages = PackageSerializer(many=True) campaign = CampaignSerializer() contacts = ContactSerializer() income = serializers.SerializerMethodField() class Meta: model = models.Order fields = '__all__' def get_income(self, instance): return 1
def report_spam(request): try: data = JSONParser().parse(request) contacts = Contact.objects.filter(mobile=data.get('mobile')) for contact in contacts: contact.report_spam(request.user) serializer = ContactSerializer(contacts, many=True) return Response({ 'status': 'success', 'data': serializer.data }, status=200) except Exception as e: return Response({'status': 'error', 'message': str(e)}, status=400)
class OrderSaleRepChartSerializer(serializers.ModelSerializer): contacts = ContactSerializer() sale_rep = MeSerializer() packages = PackageSerializer(many=True) campaign = CampaignSerializer() step_details = StepDetailWithoutOrderSerializer(many=True) history = OrderHistorySerializer(many=True) licenses = LicenseSerializer(many=True) lifetime_licenses = LifetimeLicenseSerializer(many=True) # order_packages = Order class Meta: model = models.Order fields = '__all__'
def test_get_all_contacts(self): """ This ensures that all contacts added in the setUp method exist when we make a GET request to the contacts/ endpoint """ # Retrieve response from API response = self.client.get( reverse('contacts-list', kwargs={'version': self.current_version})) # Fetch data from database expected = Contact.objects.all() serialized = ContactSerializer(expected, many=True) self.assertEqual(response.json(), serialized.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
class OrderChartSerializer(serializers.ModelSerializer): contacts = ContactSerializer() sale_rep = MeSerializer() packages = PackageSerializer(many=True) campaign = CampaignSerializer() step_details = StepDetailWithoutOrderSerializer(many=True) history = OrderHistorySerializer(many=True) licenses = LicenseSerializer(many=True) lifetime_licenses = LifetimeLicenseSerializer(many=True) amount = serializers.IntegerField(required=False) month_group = serializers.IntegerField() # order_packages = Order class Meta: model = models.Order fields = '__all__'
def search(request): if request.method == 'GET': try: term = request.query_params['q'].strip() except: return Response('Required fields: q', status=status.HTTP_400_BAD_REQUEST) try: term_query = Q(firstname__icontains=term) \ | Q(lastname__icontains=term) \ | Q(street__icontains=term) \ | Q(city__icontains=term) \ | Q(zipcode__icontains=term) result = Contact.objects.filter(term_query)[:20] except: return Response("not found", status=status.HTTP_204_NO_CONTENT) serializer_class = ContactSerializer(result, many=True) return Response(serializer_class.data, status=status.HTTP_200_OK)
def contact_list(request): if request.method == 'GET': contacts = Contact.objects.all() serializer = ContactSerializer(contacts, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ContactSerializer(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) elif request.method == 'DELETE': contact = Contact.objects.get(name=request.data.name) contact.delete() return Response(status.HTTP_204_NO_CONTENT)
def test_search_by_email(self): """ This ensures that all contacts with a defined email will be returned when a query with a part of his email is sent in a GET request to contacts/search endpoint """ # Retrieve response from API query = '@example.com' response = self.search_contacts(query) # Fetch data from database expected = Contact.objects.filter(emails__email__icontains=query) serialized = ContactSerializer(expected, many=True) response_ids = map(lambda c: c.get('id'), response.data) expected_ids = map(lambda c: c.get('id'), serialized.data) self.assertTrue( all([expected_id in response_ids for expected_id in expected_ids])) self.assertEqual(response.status_code, status.HTTP_200_OK)
def search_user_by_name(request): try: search_name = request.GET.get('name') contacts = Contact.objects.filter(full_name__icontains=search_name) start_list = [] mid_list = [] for c in contacts: if c.full_name.lower().find(search_name.lower()) == 0: start_list.append(c) else: mid_list.append(c) contacts = start_list + mid_list paginator = PageNumberPagination() paginator.page_size = 20 paginated_contacts = paginator.paginate_queryset(contacts, request) serializer = ContactSerializer(paginated_contacts, many=True) return paginator.get_paginated_response(serializer.data) except Exception as e: return Response({'status': 'error', 'message': str(e)}, status=400)
def get(self, request, name): data = None if name: data = [] registered_users = User.objects.all().filter( name__istartswith=name) contact_users = Contact.objects.filter(name__istartswith=name) registered_users_contain = User.objects.all().filter( name__icontains=name).exclude(name__istartswith=name) contact_users_contain = Contact.objects.filter( name__icontains=name).exclude(name__istartswith=name) data = UserSerializer(registered_users, many=True).data data += ContactSerializer(contact_users, many=True).data data += UserSerializer(registered_users_contain, many=True).data data += UserSerializer(contact_users_contain, many=True).data status_code = status.HTTP_200_OK else: # bad request from user data = {"message": "Name cannot be empty"} status_code = status.HTTP_400_BAD_REQUEST return Response(data=data, status=status_code)
def contact_detail(request, pk): try: contact = Contact.objects.get(pk=pk) except Contact.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ContactSerializer(contact) return Response(serializer.data) elif request.method == 'PUT': serializer = ContactSerializer(contact, 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': contact.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, phone_no): data = [] if phone_no and phone_no.isdigit(): user = User.objects.filter(phone_no=phone_no) if user.exists(): user = user.first() data = [{ "name": user.name, "phone_no": user.phone_no, "spam": user.spam }] status_code = status.HTTP_200_OK else: contacts = Contact.objects.filter(phone_no=phone_no) contact_serializer = ContactSerializer(contacts, many=True) data = contact_serializer.data status_code = status.HTTP_200_OK else: # bad request from user data = {"message": "Invalid phone number"} status_code = status.HTTP_400_BAD_REQUEST return Response(data=data, status=status_code)
class OrderSerializer(serializers.ModelSerializer): contacts = ContactSerializer() sale_rep = MeSerializer() packages = PackageSerializer(many=True) campaign = CampaignSerializer() step_details = StepDetailWithoutOrderSerializer(many=True) history = OrderHistorySerializer(many=True) all_histories = serializers.SerializerMethodField() licenses = LicenseSerializer(many=True) lifetime_licenses = LifetimeLicenseSerializer(many=True) # order_packages = Order class Meta: model = models.Order fields = '__all__' def get_all_histories(self, instance): cur_contact = instance.contacts histories = models.OrderHistory.objects.filter( order__contacts=cur_contact) serializer = OrderHistorySerializer(histories, many=True) return serializer.data
def get(self, request, format=None): contacts = Contact.objects.all() serializer = ContactSerializer(contacts, many=True) #return Response(serializer.data) return render(request, 'contacts/contact_list.html', {'contactlist': contacts})
def get(self, request, pk, format=None): contact = self.get_object(pk) serializer = ContactSerializer(contact) return Response(serializer.data)
def get_to(self, obj): contacts = obj.to contacts_serialized = ContactSerializer(contacts) return contacts_serialized.data