Example #1
0
class OrderListLocationsSerializer(serializers.ModelSerializer):
    origin = LocationSerializer()
    destiny = LocationSerializer()

    class Meta:
        model = Order
        fields = ('origin', 'destiny')
Example #2
0
class OrderListSerializer(serializers.ModelSerializer):
    driver = DriverListSerializer()
    truck = TruckSerializer()
    origin = LocationSerializer()
    destiny = LocationSerializer()

    class Meta:
        model = Order
        exclude = ('created', 'updated')
Example #3
0
    def test_wifi_location_from_json(self):
        """Test that a wifi location can be deserialized from json"""
        location_name = "Arco do CegoS"
        request = {
            "name": location_name,
            "creation_date": "2017-04-30T14:19:35.505954Z",
            "coordinate": {
                "wifiSSIDs": [{
                    "name": "edurom"
                }, {
                    "name": "thompson"
                }, {
                    "name": "house"
                }],
                "type":
                "WIFI"
            }
        }
        #data = JSONParser().parse(json)
        serializer = LocationSerializer(data=request)
        if serializer.is_valid():
            u1 = User.objects.get(username="******")
            serializer.save(user=u1)
            l = Location.objects.get(name=location_name)
            self.assertEqual(l.name, location_name, "Correct location created")
            self.assertEqual(l.coordinate.type, "WIFI",
                             "Correct coordinate added")
            for ssid in l.coordinate.wificoordinate.ssid_set.all():
                self.assertIn(ssid.name, self.ssids_arco,
                              "The ssids are persisted")

        else:
            self.fail(serializer.errors)
Example #4
0
class DetailUserSerializer(serializers.ModelSerializer):
    current_location = LocationSerializer(many=False, read_only=True)
    other_user = SimpleUserSerializer(many=False, read_only=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'matchable', 'current_location', 'other_user']
Example #5
0
class UpdateUserSerializer(serializers.ModelSerializer):
    current_location = LocationSerializer(many=False)
    other_user = SimpleUserSerializer(many=False)

    class Meta:
        model = User
        fields = ['matchable', 'current_location', 'other_user']
Example #6
0
class UserSerializer(serializers.ModelSerializer):

    sub_categories = SubCategoriesSerializer(many=True, read_only=True)
    current_location = LocationSerializer(many=False, read_only=True)
    avatar_url = serializers.SerializerMethodField('validate_avatar_url')

    # document_proof = serializers.SerializerMethodField('validate_document_url')

    class Meta:
        model = User
        # depth = 1
        fields = [
            'id', 'mobile_no', 'rating', 'name', 'avatar_url', 'is_vendor',
            'business_name', 'business_description', 'is_admin',
            'current_location', 'sub_categories'
        ]

    def validate_avatar_url(self, user):
        image = user.avatar_url
        if image:
            new_url = image.url
            if "?" in new_url:
                new_url = image.url[:image.url.rfind("?")]
            return new_url
        else:
            image = None
            return image
 def get_proposed_locations(self, match):
     proposed_locations = []
     for location in match.proposed_locations.all():
         proposed_locations.append(LocationSerializer(location).data)
     if proposed_locations == []:
         return None
     return proposed_locations
Example #8
0
    def post(self, request):

        serializer = LocationSerializer(data=request.data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.error_messages,
                        status=status.HTTP_400_BAD_REQUEST)
Example #9
0
def create_location(request):
    serializer = LocationSerializer(data=request.data["data"])
    if serializer.is_valid():
        serializer.save(user=request.user)
        return Response(JSONResponse().addData("Location",
                                               serializer.data).addData(
                                                   "status",
                                                   "Location created!").send(),
                        status=status.HTTP_201_CREATED)
    else:
        return Response(JSONResponse().addError(
            0, "Location could not be created").addError(
                1, serializer.errors).send(),
                        status=status.HTTP_400_BAD_REQUEST)
Example #10
0
class PostRetrieveSerializer(serializers.ModelSerializer):

    image = serializers.SerializerMethodField()

    def get_image(self, post):
        return get_absolute_uri(self, post)

    location = LocationSerializer()

    class Meta:
        model = Post
        fields = [
            'id', 'user', 'image', 'description', 'location', 'like', 'slug'
        ]
Example #11
0
    def post(self, request, pk):
        # Add location Data
        location_data = {
            "location": request.data['location'],
            "address": request.data['address'],
            "x_coord": request.data['x_coord'],
            "y_coord": request.data['y_coord'],
        }
        location_serializer = LocationSerializer(data=location_data)
        location_in_db = Location.objects.filter(
            location=request.data['location'])

        if not location_in_db:
            if location_serializer.is_valid():
                location_serializer.save()
                location_id = location_serializer.data['id']
            else:
                return Response(location_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            location_id = location_in_db.get().id

        # Add Case location visit history Data
        case_locations_data = {
            'case': pk,
            'location': location_id,
            'date_from': request.data['date_from'],
            'date_to': request.data['date_to'],
            'category': request.data['category']
        }
        case_locations_serializer = CaseLocationSerializer(
            data=case_locations_data)

        if case_locations_serializer.is_valid():
            case_locations_serializer.save()
            return Response(case_locations_serializer.data,
                            status=status.HTTP_201_CREATED)

        else:
            return Response(case_locations_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #12
0
class ProjectSerializer(serializers.ModelSerializer):
    descriptions = serializers.SerializerMethodField()
    members = serializers.SerializerMethodField()
    media = MediaSerializer(many=True, )
    contacts = ContactSerializer(many=True, )
    abilities = AbilitySerializer(many=True, )
    keywords = KeywordSerializer(many=True, )
    schedule = ProjectScheduleSerializer()
    location = LocationSerializer()

    class Meta:
        model = Project
        fields = (
            'id',
            'title',
            'descriptions',
            'profile_image',
            'started_at',
            'ends_at',
            'media',
            'contacts',
            'abilities',
            'keywords',
            'schedule',
            'location',
            'members',
        )

    def get_descriptions(self, obj):
        descriptions = ProjectDescription.objects.filter(project=obj.id)
        return ProjectDescriptionSerializer(descriptions, many=True).data

    def get_members(self, obj):
        members = ProjectMember.objects.filter(
            project=obj.id,
            is_active=True,
        )
        return ProjectMemberSerializer(members, many=True).data
Example #13
0
    def post(self, request, pk):
        # Add location Data
        location_data = {
            "location": request.data['location'],
            "address": request.data['address'],
            "x_coord": request.data['x_coord'],
            "y_coord": request.data['y_coord'],
        }

        location_serializer = LocationSerializer(data=location_data)

        if location_serializer.is_valid():
            location_serializer.save()
        else:
            return Response(location_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        # Add Case location visit history Data
        location_history_data = {
            'case': pk,
            'location': location_serializer.data['id'],
            'date_from': request.data['date_from'],
            'date_to': request.data['date_to'],
            'category': request.data['category']
        }
        location_history_serializer = LocationVisitHistorySerializer(
            data=location_history_data)

        if location_history_serializer.is_valid():
            location_history_serializer.save()
            return Response(location_history_serializer.data,
                            status=status.HTTP_201_CREATED)

        else:
            return Response(location_history_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
 def get_meeting_location(self, match):
     meeting_location = LocationSerializer(match.meeting_location).data
     if meeting_location == {}:
         return None
     return meeting_location
Example #15
0
def list_locations(request):
    serializer = LocationSerializer(Location.objects.all(), many=True)
    return Response(JSONResponse().addData("Locations",
                                           serializer.data).send(),
                    status=status.HTTP_200_OK)
Example #16
0
 def get(self, request):
     locations = Location.objects.all()
     serializer = LocationSerializer(locations, many=True)
     return Response({"data": serializer.data}, status=status.HTTP_200_OK)
Example #17
0
 def get_location(self, obj):
     if obj.location:
         return LocationSerializer(obj.location.all(), many=True).data
     return None
Example #18
0
class SimpleUserSerializer(serializers.ModelSerializer):
    current_location = LocationSerializer(many=False)

    class Meta:
        model = User
        fields = ['matchable', 'current_location', 'id', 'email']
Example #19
0
 def get(self, request):
     last = Location.objects.last()
     serializer = LocationSerializer(last)
     return Response(serializer.data, status=status.HTTP_200_OK)
class UserSerializer(serializers.ModelSerializer):
    """Serializer with current match."""

    net_id = serializers.CharField(source="person.net_id")
    majors = MajorSerializer(source="person.majors", many=True)
    hometown = serializers.CharField(source="person.hometown")
    profile_pic_url = serializers.CharField(source="person.profile_pic_url")
    facebook_url = serializers.CharField(source="person.facebook_url")
    instagram_username = serializers.CharField(
        source="person.instagram_username")
    graduation_year = serializers.CharField(source="person.graduation_year")
    pronouns = serializers.CharField(source="person.pronouns")
    purposes = PurposeSerializer(source="person.purposes", many=True)
    availability = SerializerMethodField("get_availability")
    locations = LocationSerializer(source="person.locations", many=True)
    interests = InterestSerializer(source="person.interests", many=True)
    groups = GroupSerializer(source="person.groups", many=True)
    prompts = SerializerMethodField("get_prompts")
    has_onboarded = serializers.BooleanField(source="person.has_onboarded")
    pending_feedback = serializers.BooleanField(
        source="person.pending_feedback")
    current_match = serializers.SerializerMethodField("get_current_match")
    deleted = serializers.BooleanField(source="person.soft_deleted")
    blocked_users = SerializerMethodField("get_blocked_users")
    is_paused = serializers.BooleanField(source="person.is_paused")
    pause_expiration = serializers.DateTimeField(
        source="person.pause_expiration")
    last_active = serializers.DateTimeField(source="person.last_active")

    def get_availability(self, user):
        if user.person.availability is None:
            return []
        availability = json.loads(user.person.availability)
        return availability

    def get_current_match(self, user):
        blocked_ids = user.person.blocked_users.values_list("id", flat=True)
        matches = Match.objects.filter(Q(user_1=user) | Q(
            user_2=user)).order_by("-created_date")
        if (len(matches) == 0 or matches[0].user_1.id in blocked_ids
                or matches[0].user_2.id in blocked_ids):
            return None
        return MatchSerializer(matches.first(), user=user).data

    def get_prompts(self, user):
        prompt_questions = user.person.prompt_questions.all()
        prompt_answers = user.person.prompt_answers
        if prompt_answers is None:
            return []
        prompt_answers = json.loads(prompt_answers)
        prompts = []
        for question_index in range(len(prompt_questions)):
            prompts.append({
                "id":
                prompt_questions[question_index].id,
                "question_name":
                prompt_questions[question_index].question_name,
                "question_placeholder":
                prompt_questions[question_index].question_placeholder,
                "answer":
                prompt_answers[question_index],
            })
        return prompts

    def get_blocked_users(self, user):
        return map(lambda u: u.id, user.person.blocked_users.all())

    class Meta:
        model = User
        fields = (
            "id",
            "net_id",
            "first_name",
            "last_name",
            "majors",
            "hometown",
            "profile_pic_url",
            "facebook_url",
            "instagram_username",
            "graduation_year",
            "pronouns",
            "purposes",
            "availability",
            "locations",
            "interests",
            "groups",
            "prompts",
            "has_onboarded",
            "deleted",
            "pending_feedback",
            "current_match",
            "blocked_users",
            "is_paused",
            "pause_expiration",
            "last_active",
        )
        read_only_fields = fields
 def get_proposed_locations(self, match):
     return (LocationSerializer(match.proposed_locations.all(),
                                many=True).data or None)
 def get_meeting_location(self, match):
     meeting_location = LocationSerializer(match.meeting_location).data
     return meeting_location or None
Example #23
0
    def post(self, request):
        user_field = [
            'id', 'username', 'password', 'email', 'first_name', 'last_name',
            'date_joined', 'last_login', 'user_type', 'bazaar_point', 'company'
        ]
        user_dict = {}
        location_dict = {}
        for fields in request.data:
            if fields in user_field:
                user_dict[fields] = request.data[fields]
            else:
                location_dict[fields] = request.data[fields]
        serializer = UserSerializer(data=user_dict)

        if serializer.is_valid():
            # There error handling part might not be required, additional test is needed
            if not "user_type" in serializer.validated_data.keys():
                return Response({"user_type": ["This field is required."]},
                                status=status.HTTP_400_BAD_REQUEST)
            if not "username" in serializer.validated_data.keys():
                return Response({"username": ["This field is required."]},
                                status=status.HTTP_400_BAD_REQUEST)
            if not "password" in serializer.validated_data.keys():
                return Response({"password": ["This field is required."]},
                                status=status.HTTP_400_BAD_REQUEST)
            email = serializer.validated_data['username']

            serializer.save()
            user = User.objects.get(username=email)

            if request.data['user_type'] == 2 or request.data[
                    'user_type'] == '2':
                if not "company" in request.data:
                    user.delete()
                    return Response({"company": ["This field is required."]},
                                    status=status.HTTP_400_BAD_REQUEST)
                location_dict['user'] = user.id
                serializer2 = LocationSerializer(data=location_dict)
                if serializer2.is_valid():
                    serializer2.save()
                else:
                    user.delete()
                    return Response({"location": ["bad location request."]},
                                    status=status.HTTP_400_BAD_REQUEST)

            user.is_active = False
            user.save()

            uidb64 = urlsafe_base64_encode(force_bytes(user.pk))

            domain = get_current_site(request).domain
            # link = reverse('activate', kwargs={'uidb64': uidb64})

            activate_url = 'http://' + "3.121.223.52:3000" + "/activate=" + str(
                uidb64)

            email_subject = 'Activate'
            email_body = 'Hi,\nPlease use this link to verify your account:\n' + activate_url
            email = EmailMessage(
                email_subject,
                email_body,
                '*****@*****.**',
                [email],
            )
            try:
                email.send(fail_silently=False)
                return Response(
                    {
                        "message":
                        "An mail has been sent to your email, please check it"
                    },
                    status=status.HTTP_201_CREATED)
            except:
                user.delete()
                return Response({"email": ["Couldn't send email"]},
                                status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(serializer._errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #24
0
def ws_message(message):
    ls = LocationSerializer(data=json.loads(message['text']))
    if ls.is_valid(raise_exception=True):
        ls.save(owner=message.user)
    else:
        pass # TODO Send error message