def to_representation(self, instance): # instance is the model object. create the custom json format by accessing instance attributes normaly and return it data = dict() pointer_serializer = PointerSerializerData(instance) member_list = Member.objects.going_members_without_active_user( instance, self.user) try: pointed = Member.objects.get(pointer=instance, user=self.user) pointed_serial = MemberSerializer(pointed) except: pointed_serial = None member_serializer = MemberSerializer(member_list, many=True) for attr, value in instance.__dict__.items(): if not attr.startswith('_'): data[attr] = value representation = { 'pointer': pointer_serializer.data, 'pointed': pointed_serial.data if pointed_serial != None else '', 'members': member_serializer.data } return representation
def create(self, request): data = request.data serializer = MemberSerializer(data=data) if serializer.is_valid(): data = Member.validate_data(data) else: log.critical(serializer.errors) return Response({'error': 'Oops! Something is wrong in your request data: {}'.format(serializer.errors)}, status=status.HTTP_400_BAD_REQUEST) log.info('posted data: {}'.format(data)) # #841 : We need to connect to Cyclos before doing Dolibarr calls, making sure Cyclos token is still valid. # This way, we avoid creating a member in Dolibarr if it's not the case. try: self.cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) # Dolibarr: Register member response_obj = self.dolibarr.post(model=self.model, data=data, api_key=request.user.profile.dolibarr_token) log.info(response_obj) # Cyclos: Register member create_user_data = { 'group': str(settings.CYCLOS_CONSTANTS['groups']['adherents_sans_compte']), 'name': '{} {}'.format(data['firstname'], data['lastname']), 'username': data['login'], 'skipActivationEmail': True, } self.cyclos.post(method='user/register', data=create_user_data) return Response(response_obj, status=status.HTTP_201_CREATED)
def test_member_is_created(self): serial_user = UserSerializer(self.user2) serial = MemberSerializer(data={'user': serial_user.data, 'pointer': self.point.pk}) self.assertTrue(serial.is_valid()) serial.save() # 2 plus pointer author self.assertEqual(Member.objects.all().count(), 2)
def create(self, request): data = request.data serializer = MemberSerializer(data=data) if serializer.is_valid(): data = Member.validate_data(data) else: log.critical(serializer.errors) return Response( { 'error': 'Oops! Something is wrong in your request data: {}'.format( serializer.errors) }, status=status.HTTP_400_BAD_REQUEST) log.info('posted data: {}'.format(data)) # #841 : We need to connect to Cyclos before doing Dolibarr calls, making sure Cyclos token is still valid. # This way, we avoid creating a member in Dolibarr if it's not the case. try: self.cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='bdc') except CyclosAPIException: return Response({'error': 'Unable to connect to Cyclos!'}, status=status.HTTP_400_BAD_REQUEST) # Dolibarr: Register member response_obj = self.dolibarr.post( model=self.model, data=data, api_key=request.user.profile.dolibarr_token) log.info(response_obj) # Cyclos: Register member create_user_data = { 'group': str(settings.CYCLOS_CONSTANTS['groups']['adherents_sans_compte']), 'name': '{} {}'.format(data['firstname'], data['lastname']), 'username': data['login'], 'skipActivationEmail': True, } self.cyclos.post(method='user/register', data=create_user_data) if data['email']: # Activate user pre-selected language # TODO: Ask member for his prefered lang # activate(data['options_langue']) # Translate subject & body for this email subject = _('Votre adhésion à Euskal Moneta') body = render_to_string('mails/create_member.txt', {'user': data}) sendmail_euskalmoneta(subject=subject, body=body, to_email=data['email']) return Response(response_obj, status=status.HTTP_201_CREATED)
class TeamSerializer(serializers.ModelSerializer): """Serialize Team model""" members = MemberSerializer(read_only=True, many=True) heads = MemberSerializer(read_only=True, many=True) class Meta: model = models.Team fields = ('id', 'name', 'heads', 'members') read_only_fields = ('id', )
def put(self, request, pk, format=None): """ Edit a Member. """ member = self.get_member(pk) self.check_object_permissions(request, member) serializer = MemberSerializer(member, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserInlineSerializer(serializers.ModelSerializer): member = MemberSerializer(source='user_member') member_type = MemberTypeSerializer(source='user_member.member_type') class Meta: model = User fields = ('id', 'email', 'member', 'member_type')
class WorkPlanSerializer(serializers.ModelSerializer): completed_by = MemberSerializer() class Meta: model = WorkPlan fields = "__all__" depth = 1
def create(self, request, **kwargs): serializer = AddMemberSerializer(data=request.data) serializer.is_valid(raise_exception=True) id = request.user adder = User.objects.get(username=id) semester = get_semester_of_date(datetime.datetime.now()) lifetime = serializer.data["lifetime"] try: user = User.objects.get(email=serializer.data["email"]) except Exception: user = None member = Member( seller=adder, last_edited_by=adder, semester=semester, name=serializer.data["name"], lifetime=serializer.data["lifetime"], email=serializer.data["email"], honorary=False, ) if "uio_username" in serializer.data: member.uio_username = serializer.data["uio_username"] if user is not None: member.user = user if lifetime: member.date_lifetime = timezone.now() member.save() return Response(MemberSerializer(member).data, status=status.HTTP_201_CREATED)
def test_get_valid_single_puppy(self): response = client.get( reverse('members-detail', kwargs={'pk': self.member.pk})) member = Member.objects.get(pk=self.member.pk) serializer = MemberSerializer(member) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def list(self, request, *args, **kwargs): objects = self.dolibarr.get( model=self.model, api_key=request.user.profile.dolibarr_token) paginator = CustomPagination() result_page = paginator.paginate_queryset(objects, request) serializer = MemberSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
class ActivitySerializerDetailed(serializers.ModelSerializer): workplace = WorkplaceSerializer() member = MemberSerializer() class Meta: model = Activity fields = ("id", "member", "workplace", "start_at", "end_at", "is_just_staying")
class AchievementSerializer(serializers.ModelSerializer): """Serialize Achievement model""" members = MemberSerializer(read_only=True, many=True) class Meta: model = models.Achievement fields = ('id', 'title', 'sub_title', 'content', 'members') read_only_fields = ('id', )
class ProjectSerializer(serializers.ModelSerializer): """Serialize Project model""" members = MemberSerializer(read_only=True, many=True) class Meta: model = models.Project fields = ('id', 'name', 'description', 'members', 'github_link', 'funding', 'faculty', 'extra') read_only_fields = ('id', )
def post(self, request, format=None): serializer = VerifySerializer(data=request.data) serializer.is_valid(raise_exception=True) try: self.member = Member.objects.get( email=serializer.data['email'], password=serializer.data['password']) except Exception as e: raise ValidationError('Email or password is wrong!.') serialized_member = MemberSerializer(serializer.member).data serialized_member['token'] = Token.objects.get(user=self.member).key return Response(serialized_member)
def MemberList(request): if request.method == 'GET': contacts = Member.objects.all() serializer = MemberSerializer(contacts, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = MemberSerializer(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 post(self, request, format=None): serializer = RegistrationDataSerializer(data=request.data, many=False) serializer.is_valid(raise_exception=True) new_user = serializer.save() raw_code = request.data["registration_code"] raw_password = request.data["password"] used_code_set = RegistrationCode.objects.filter(code=raw_code) if used_code_set[0].onetime: used_code_set.delete() new_user.set_password(raw_password) # new_user.is_active = False new_user.save() # new_user.email_user("hello", "po") return Response(MemberSerializer(new_user).data)
def member_detail(request, pk): """ Allows operations on a specific member id such as GET, PUT, and DELETE. Will return the http status and json data if applicable. """ try: member = Member.objects.get(pk=pk) except Member.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = MemberSerializer(member) return JsonResponse(serializer.data) elif request.method == 'PATCH': data = JSONParser().parse(request) response = member.update(data) if response != None: return HttpResponse(status=400) serializer = MemberSerializer(member) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = MemberSerializer(member, data=data) print(data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': member.delete() return HttpResponse(status=204)
def to_representation(self, instance): # instance is the model object. create the custom json format by accessing instance attributes normaly and return it data = dict() pointer_serializer = PointerSerializerData(instance) member_list = Member.objects.going_members(instance) member_serializer = MemberSerializer(member_list, many=True) # getting only needed attributes for attr, value in instance.__dict__.items(): if not attr.startswith('_'): data[attr] = value representation = { 'pointer': pointer_serializer.data, 'members': member_serializer.data } return representation
def assign_to_project(self, request, pk=None): """ URL: /members/{id}/assign_to_project/ :param pk: id of the member we're assigning to the project :return: Response """ member = get_object_or_404(Member, pk=pk) project = get_object_or_404(Project, pk=request.data['id']) serializer = MemberSerializer(member) if member.is_available: member.project = project member.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response( {"message": "Member can't be assigned to the project now"})
def member_list(request): """ Allows for GET requests for all members and POST requests to add member(s) to the db. Will return the http status code and json data if applicable. """ if request.method == 'GET': members = Member.objects.all() serializer = MemberSerializer(members, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = MemberSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def update(self, request, *args, **kwargs): member = self.get_object() member.name = request.data["name"] member.email = request.data["email"] member.last_edited_by = User.objects.get(username=request.user) lifetime = request.data["lifetime"] == "true" if lifetime and not member.lifetime: member.date_lifetime = timezone.now() member.lifetime = True elif (not lifetime) and member.lifetime: member.date_lifetime = None member.lifetime = False if "honorary" in request.data: member.honorary = request.data["honorary"] == "true" if "comments" in request.data: member.comments = request.data["comments"] member.save() return Response(MemberSerializer(member).data, status=status.HTTP_200_OK)
def test_get_all_members(self): response = client.get(reverse('members-list')) members = Member.objects.all() serializer = MemberSerializer(members, many=True) self.assertEqual(response.data['results'], serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def list(self, request): email = request.GET.get('email', '') login = request.GET.get('login', '') name = request.GET.get('name', '') valid_login = Member.validate_num_adherent(login) dolibarr_token = request.user.profile.dolibarr_token if login and valid_login: # We want to search in members by login (N° Adhérent) try: response = self.dolibarr.get(model='members', login=login, api_key=dolibarr_token) except DolibarrAPIException: return Response(status=status.HTTP_204_NO_CONTENT) return Response(response) elif login and not valid_login: return Response( { 'error': 'You need to provide a *VALID* ?login parameter! (Format: E12345)' }, status=status.HTTP_400_BAD_REQUEST) elif name and len(name) >= 3: # We want to search in members by name (Firstname and Lastname) try: response = self.dolibarr.get(model='members', name=name, api_key=dolibarr_token) except DolibarrAPIException: return Response(status=status.HTTP_204_NO_CONTENT) return Response(response) elif name and len(name) < 3: return Response( { 'error': 'You need to provide a ?name parameter longer than 2 characters!' }, status=status.HTTP_400_BAD_REQUEST) elif email: try: validate_email(email) user_results = self.dolibarr.get(model='members', email=email, api_key=dolibarr_token) user_data = [ item for item in user_results if item['email'] == email ][0] return Response(user_data) except forms.ValidationError: return Response( { 'error': 'You need to provide a *VALID* ?email parameter! (Format: E12345)' }, status=status.HTTP_400_BAD_REQUEST) else: objects = self.dolibarr.get(model=self.model, api_key=dolibarr_token) paginator = CustomPagination() result_page = paginator.paginate_queryset(objects, request) serializer = MemberSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def get(self, request, pk, format=None): member_list = self.get_object(pk) serializer = MemberSerializer(member_list, many=True) return Response(serializer.data)
def list(self, request): email = request.GET.get('email', '') login = request.GET.get('login', '') name = request.GET.get('name', '') valid_login = Member.validate_num_adherent(login) token = request.GET.get('token', '') # Si un token est fourni pour récupérer un adhérent, la # recherche peut être faite de manière anonyme, sinon il faut # être authentifié, afin d'éviter la fuite d'information sur les # adhérents. if token and not request.user.is_authenticated: dolibarr = DolibarrAPI() dolibarr_token = dolibarr.login(login=settings.APPS_ANONYMOUS_LOGIN, password=settings.APPS_ANONYMOUS_PASSWORD) else: dolibarr_token = request.user.profile.dolibarr_token if login and valid_login: # We want to search in members by login (N° Adhérent) try: response = self.dolibarr.get(model='members', sqlfilters="login='******'".format(login), api_key=dolibarr_token) except DolibarrAPIException: return Response(status=status.HTTP_204_NO_CONTENT) return Response(response) elif login and not valid_login: return Response({'error': 'You need to provide a *VALID* ?login parameter! (Format: E12345)'}, status=status.HTTP_400_BAD_REQUEST) elif name and len(name) >= 3: # We want to search in members by name (firstname, lastname or societe) try: sqlfilters = "(firstname like '%25{name}%25' or lastname like '%25{name}%25' or societe like '%25{name}%25') and statut=1".format(name=name) response = self.dolibarr.get(model='members', sqlfilters=sqlfilters, api_key=dolibarr_token) except DolibarrAPIException: return Response(status=status.HTTP_204_NO_CONTENT) return Response(response) elif name and len(name) < 3: return Response({'error': 'You need to provide a ?name parameter longer than 2 characters!'}, status=status.HTTP_400_BAD_REQUEST) elif email: try: validate_email(email) user_results = self.dolibarr.get(model='members', sqlfilters="email='{}' and statut=1".format(email), api_key=dolibarr_token) user_data = [item for item in user_results if item['email'] == email][0] return Response(user_data) except forms.ValidationError: return Response({'error': 'You need to provide a *VALID* ?email parameter! (Format: E12345)'}, status=status.HTTP_400_BAD_REQUEST) elif token: try: response = self.dolibarr.get(model='members', token=token, api_key=dolibarr_token) except DolibarrAPIException: return Response(status=status.HTTP_204_NO_CONTENT) return Response(response) else: objects = self.dolibarr.get(model='members', sqlfilters="statut=1", api_key=dolibarr_token) paginator = CustomPagination() result_page = paginator.paginate_queryset(objects, request) serializer = MemberSerializer(result_page, many=True) return paginator.get_paginated_response(serializer.data)
def test_member(self): member = Member.objects.filter(user=self.user1) serializer = MemberSerializer(member, many=True) self.assertEqual(serializer.data[0]['pointer'], self.point.pk)