class OrganizationRetrieveSerializer(ChannelRelationshipSerializer): address = address_serializers[1]() image = UploadedImageSerializer() cover = UploadedImageSerializer() causes = CauseSerializer(many=True) owner = UserOrganizationRetrieveSerializer() galleries = GalleryRetrieveSerializer(many=True) is_bookmarked = serializers.SerializerMethodField() projects_count = serializers.SerializerMethodField() channel = ChannelRetrieveSerializer() class Meta: model = models.Organization fields = ['id', 'slug', 'owner', 'document', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type', 'image', 'cover', 'published', 'hidden_address', 'causes', 'galleries', 'contact_name', 'contact_phone', 'contact_email', 'is_bookmarked', 'verified', 'projects_count', 'rating', 'benefited_people', 'channel'] def get_is_bookmarked(self, instance): user = self.context['request'].user if user.is_authenticated(): return instance.is_bookmarked(user) return False def get_projects_count(self, instance): total = 0 try: total = Project.objects.filter(organization=instance, published=True).count() except: pass return total @hide_address def to_representation(self, instance): return super(OrganizationRetrieveSerializer, self).to_representation(instance)
def create(self, request, *args, **kwargs): """ Upload image. """ upload_data = {} if request.data.get('image', None): upload_data['image'] = request.data.get('image') upload_header = request.META.get('HTTP_X_UNAUTHENTICATED_UPLOAD', None) is_authenticated = request.user.is_authenticated() if request.data.get('crop_rect', None): crop_rect = request.data.get('crop_rect') if isinstance(crop_rect, str): crop_rect = json.loads(crop_rect) upload_data['image'] = perform_image_crop(upload_data['image'], crop_rect) request.FILES['image'] = upload_data['image'] if is_authenticated or upload_header: if upload_header: upload_data['user'] = None if is_authenticated: upload_data['user'] = request.user.id serializer = UploadedImageSerializer(data=upload_data, context=self.get_serializer_context()) if serializer.is_valid(): self.object = serializer.save() headers = self.get_success_headers(serializer.data) return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return response.Response(status=status.HTTP_401_UNAUTHORIZED)
class ProjectRetrieveSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() address = address_serializers[1]() organization = OrganizationSearchSerializer() disponibility = DisponibilitySerializer() roles = VolunteerRoleSerializer(many=True) owner = UserProjectRetrieveSerializer() applies = ProjectAppliesSerializer(many=True, source="active_apply_set") causes = FullCauseSerializer(many=True) skills = SkillSerializer(many=True) galleries = GalleryRetrieveSerializer(many=True) documents = UploadedDocumentSerializer(many=True) categories = CategoryRetrieveSerializer(many=True) posts = serializers.SerializerMethodField('get_posts_list') is_bookmarked = serializers.SerializerMethodField() bookmark_count = serializers.SerializerMethodField() item = ItemSerializer() channel = ChannelRetrieveSerializer() class Meta: model = models.Project fields = [ 'slug', 'image', 'name', 'description', 'highlighted', 'published_date', 'address', 'details', 'created_date', 'organization', 'disponibility', 'roles', 'owner', 'minimum_age', 'applies', 'applied_count', 'max_applies', 'max_applies_from_roles', 'closed', 'closed_date', 'published', 'hidden_address', 'crowdfunding', 'public_project', 'causes', 'skills', 'categories', 'posts', 'is_bookmarked', 'bookmark_count', 'item', 'type', 'rating', 'benefited_people', 'chat_enabled', 'canceled', 'channel', 'galleries', 'documents' ] def get_is_bookmarked(self, instance): user = self.context['request'].user if user.is_authenticated(): return instance.is_bookmarked(user) return False def get_bookmark_count(self, instance): is_bookmark_count_enabled = int( get_channel_setting(self.context['request'].channel, "ENABLE_PROJECT_BOOKMARK_COUNT")[0]) if is_bookmark_count_enabled: return instance.bookmark_count() return None def get_posts_list(self, instance): posts = instance.posts.filter(deleted=False).order_by("-pk") return PostRetrieveSerializer(posts, many=True, context=self.context).data @add_current_user_is_applied_representation @hide_address @add_disponibility_representation def to_representation(self, instance): return super(ProjectRetrieveSerializer, self).to_representation(instance)
class UserApplyRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() profile = get_profile_serializers()[1]() class Meta: model = models.User fields = ['uuid', 'name', 'slug', 'avatar', 'phone', 'phone2', 'email', 'profile', 'rating']
class CurrentUserSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() profile = get_profile_serializers()[1]() organizations = OrganizationOwnerRetrieveSerializer(many=True, source='active_organizations') rating_requests_user_count = serializers.SerializerMethodField() rating_requests_project_count = serializers.SerializerMethodField() rating_requests_projects_with_unrated_users = serializers.SerializerMethodField() chat_enabled = serializers.SerializerMethodField() class Meta: model = models.User fields = ['uuid', 'name', 'phone', 'phone2', 'avatar', 'email', 'locale', 'profile', 'slug', 'public', 'organizations', 'rating_requests_user_count', 'rating_requests_project_count', 'rating_requests_projects_with_unrated_users', 'is_subscribed_to_newsletter', 'chat_enabled'] def get_chat_enabled(self, obj): applies = Apply.objects.filter(project__published=True, project__chat_enabled=True, user=obj) return applies.count() > 0 def get_rating_requests_user_count(self, obj): return obj.rating_requests.filter(deleted_date=None, rating=None, content_type__model="user").count() def get_rating_requests_project_count(self, obj): return obj.rating_requests.filter(deleted_date=None, rating=None, content_type__model="project").count() def get_rating_requests_projects_with_unrated_users(self, obj): return len(obj.rating_requests.filter(deleted_date=None, rating=None, content_type__model="user", initiator_type__model="project").values_list("initiator_id", flat=True).distinct()) @expired_password def to_representation(self, *args, **kwargs): return super(CurrentUserSerializer, self).to_representation(*args, **kwargs)
class ProjectSearchSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() address = address_serializers[1]() organization = CompactOrganizationSerializer() owner = ShortUserPublicRetrieveSerializer() disponibility = DisponibilitySerializer() categories = CategoryRetrieveSerializer(many=True) is_bookmarked = serializers.BooleanField() causes = FullCauseSerializer(many=True) skills = SkillSerializer(many=True) channel = ChannelRetrieveSerializer() class Meta: model = models.Project fields = [ 'slug', 'image', 'name', 'description', 'disponibility', 'highlighted', 'published_date', 'address', 'organization', 'owner', 'applied_count', 'max_applies', 'hidden_address', 'categories', 'is_bookmarked', 'published', 'closed', 'causes', 'skills', 'rating', 'chat_enabled', 'canceled', 'channel' ] @hide_address @add_disponibility_representation def to_representation(self, instance): return super(ProjectSearchSerializer, self).to_representation(instance)
class ProjectOnOrganizationRetrieveSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() address = address_serializers[1]() disponibility = DisponibilitySerializer() causes = CauseSerializer(many=True) skills = SkillSerializer(many=True) owner = UserProjectRetrieveSerializer() organization = CompactOrganizationSerializer() class Meta: model = models.Project fields = [ 'slug', 'image', 'name', 'description', 'highlighted', 'published_date', 'address', 'details', 'created_date', 'disponibility', 'minimum_age', 'applied_count', 'max_applies', 'max_applies_from_roles', 'closed', 'closed_date', 'published', 'hidden_address', 'crowdfunding', 'public_project', 'causes', 'skills', 'owner', 'organization', 'rating' ] @hide_address @add_disponibility_representation def to_representation(self, instance): return super(ProjectOnOrganizationRetrieveSerializer, self).to_representation(instance)
class UserSearchSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() profile = get_profile_serializers()[2]() class Meta: model = models.User fields = ['slug', 'name', 'avatar', 'profile']
class GalleryRetrieveSerializer(ChannelRelationshipSerializer): images = UploadedImageSerializer(many=True) class Meta: model = Gallery fields = ('id', 'uuid', 'owner', 'name', 'description', 'images') read_only_fields = ('uuid', ) extra_kwargs = {'owner': {'write_only': True}}
class ItemImageSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer(read_only=True) image_id = serializers.IntegerField(required=False) class Meta: model = ItemImage fields = ['id', 'image', 'image_id', 'item'] extra_kwargs = {'item': {'write_only': True}}
class OrganizationOwnerRetrieveSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() causes = CauseSerializer(many=True) address = address_serializers[1]() class Meta: model = models.Organization fields = ['slug', 'name', 'description', 'image', 'id', 'causes', 'address']
class OrganizationSearchSerializer(ChannelRelationshipSerializer): address = address_serializers[1]() image = UploadedImageSerializer() is_bookmarked = serializers.BooleanField() channel = ChannelRetrieveSerializer() class Meta: model = models.Organization fields = ['id', 'slug', 'owner', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type', 'image', 'is_bookmarked', 'verified', 'rating', 'channel']
def test_image_urls(self): """Assert that image object returns url""" user = get_user_model().objects.create_user('*****@*****.**', 'validpassword', object_channel="default") client = APIClient() client.force_authenticate(user=user) image = Image.new('RGB', (100, 100)) tmp_file = NamedTemporaryFile(suffix=".jpg") image.save(tmp_file, format="JPEG") tmp_file.seek(0) # otherwise we start reading at the end data = { 'image': tmp_file } response = client.post(reverse('upload-images-list'), data, format="multipart") self.assertTrue(response.status_code == 201) img_id = response.data['id'] img = UploadedImage.objects.get(pk=img_id) factory = APIRequestFactory() request = factory.post('/') serializer = UploadedImageSerializer(instance=img, context={'request': request}) media_path = getattr(settings, "MEDIA_URL") if media_path == "": media_path = "/" test_url = 'http://testserver{media_path}user-uploaded/images'.format(media_path=media_path) self.assertTrue(test_url in serializer.get_image_url(img)) self.assertTrue(test_url in serializer.get_image_small_url(img)) self.assertTrue(test_url in serializer.get_image_medium_url(img)) self.assertTrue(test_url in serializer.get_image_large_url(img)) self.assertTrue(img.uuid in serializer.get_image_url(img)) self.assertTrue(img.uuid in serializer.get_image_small_url(img)) self.assertTrue(img.uuid in serializer.get_image_medium_url(img)) self.assertTrue(img.uuid in serializer.get_image_large_url(img))
class LongUserPublicRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() profile = get_profile_serializers()[1]() applies = ApplyUserRetrieveSerializer(many=True, source="apply_set") bookmarked_projects = BookmarkUserRetrieveSerializer(many=True, source="projectbookmark_set") volunteer_hours = serializers.SerializerMethodField() class Meta: model = models.User fields = ['name', 'avatar', 'profile', 'slug', 'applies', 'bookmarked_projects', 'volunteer_hours', 'rating'] def get_volunteer_hours(self, obj): volunteer_hours = timezone.timedelta(hours=0) applies = Apply.objects.filter(user=obj).all() for a in applies: if hasattr(a.project, 'job'): jobs = a.project.job.dates for job in jobs.values(): volunteer_hours += job['end_date'] - job['start_date'] elif hasattr(a.project, 'work'): if a.project.closed: last_time = a.project.closed_date else: last_time = timezone.now() try: weeks = (last_time - a.date).days // 7 project_hours = a.project.work.weekly_hours if a.project.work.weekly_hours is not None else 0 project_hours = project_hours * (weeks+1) volunteer_hours += timezone.timedelta(hours=project_hours) except: pass resp = (volunteer_hours.days * 24) + (volunteer_hours.seconds // 3600) return resp def to_representation(self, *args, **kwargs): ret = super(LongUserPublicRetrieveSerializer, self).to_representation(*args, **kwargs) is_bookmarked_projects_on_user_enabled = int(get_channel_setting(self.context['request'].channel, "ENABLE_PUBLIC_USER_BOOKMARKED_PROJECTS")[0]) if not is_bookmarked_projects_on_user_enabled: ret["bookmarked_projects"] = None return ret
class ProjectBookmarkRetrieveSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() address = address_serializers[1]() organization = OrganizationSearchSerializer() disponibility = DisponibilitySerializer() class Meta: model = models.Project fields = [ 'slug', 'image', 'name', 'description', 'highlighted', 'published_date', 'address', 'created_date', 'organization', 'minimum_age', 'applied_count', 'max_applies', 'max_applies_from_roles', 'closed', 'closed_date', 'published', 'hidden_address', 'crowdfunding', 'public_project', 'disponibility' ] @add_disponibility_representation def to_representation(self, instance): return super(ProjectBookmarkRetrieveSerializer, self).to_representation(instance)
class ProjectCreateUpdateSerializer(ChannelRelationshipSerializer): address = address_serializers[0]() disponibility = DisponibilitySerializer() roles = VolunteerRoleSerializer(many=True, required=False) causes = CauseAssociationSerializer(many=True, required=False) skills = SkillAssociationSerializer(many=True, required=False) categories = CategoryAssociationSerializer(many=True, required=False) galleries = GalleryAssociationSerializer(many=True, required=False) documents = UploadedDocumentAssociationSerializer(many=True, required=False) image = UploadedImageSerializer(read_only=True) image_id = serializers.IntegerField(required=False) organization = OrganizationRetrieveSerializer(read_only=True) organization_id = serializers.IntegerField(required=False) item_id = serializers.IntegerField(required=False) class Meta: model = models.Project fields = [ 'id', 'image', 'image_id', 'name', 'slug', 'owner', 'details', 'description', 'highlighted', 'published', 'published_date', 'created_date', 'address', 'organization', 'organization_id', 'disponibility', 'roles', 'max_applies', 'minimum_age', 'hidden_address', 'crowdfunding', 'public_project', 'causes', 'skills', 'type', 'item_id', 'benefited_people', 'galleries', 'testimony', 'documents', 'categories' ] read_only_fields = [ 'slug', 'highlighted', 'published', 'published_date', 'created_date' ] def validate(self, data): required_organization(self.context["request"], data.get("organization_id", None)) project_owner_is_organization_member_or_self( self.context["request"], data.get("organization_id", None)) return super(ProjectCreateUpdateSerializer, self).validate(data) def create(self, validated_data): causes = validated_data.pop('causes', []) categories = validated_data.pop('categories', []) skills = validated_data.pop('skills', []) documents = validated_data.pop('documents', []) galleries = validated_data.pop('galleries', []) # Address address_data = validated_data.pop('address', {}) address_sr = address_serializers[0](data=address_data, context=self.context) address = address_sr.create(address_data) validated_data['address'] = address # We gotta pop some fields before creating project roles = validated_data.pop('roles', []) disp = validated_data.pop('disponibility', {}) # Create project project = super(ProjectCreateUpdateSerializer, self).create(validated_data) # Roles for role_data in roles: role_sr = VolunteerRoleSerializer(data=role_data, context=self.context) role = role_sr.create(role_data) project.roles.add(role) # Disponibility if disp['type'] == 'work': work_data = disp['work'] work_data['project'] = project work_sr = WorkSerializer(data=work_data, context=self.context) work = work_sr.create(work_data) if disp['type'] == 'job': job_data = disp['job'] job_data['project'] = project job_sr = JobSerializer(data=job_data, context=self.context) job = job_sr.create(job_data) # Associate causes for cause in causes: c = core_models.Cause.objects.get(pk=cause['id']) project.causes.add(c) # Associate categories for category in categories: c = models.Category.objects.get(pk=category['id']) project.categories.add(c) # Associate galleries for gallery in galleries: c = Gallery.objects.get(pk=gallery['id']) project.galleries.add(c) # Associate skills for skill in skills: s = core_models.Skill.objects.get(pk=skill['id']) project.skills.add(s) # Associate documents for document in documents: d = UploadedDocument.objects.get(pk=document['id']) project.documents.add(d) return project def update(self, instance, validated_data): causes = validated_data.pop('causes', []) skills = validated_data.pop('skills', []) categories = validated_data.pop('categories', []) documents = validated_data.pop('documents', []) galleries = validated_data.pop('galleries', []) address_data = validated_data.pop('address', None) roles = validated_data.pop('roles', None) disp = validated_data.pop('disponibility', None) instance.item_id = validated_data.get('item_id', None) # Save related resources if address_data: address_sr = address_serializers[0](data=address_data, context=self.context) address = address_sr.create(address_data) instance.address = address if roles: instance.roles.clear() for role_data in roles: identifier = role_data.pop("id") if "id" in role_data else None role_sr = VolunteerRoleSerializer(data=role_data, context=self.context) try: role_instance = models.VolunteerRole.objects.get( pk=identifier) role = role_sr.update(role_instance, role_data) except: role = role_sr.create(role_data) instance.roles.add(role) if disp: models.Work.objects.filter(project=instance).delete() models.Job.objects.filter(project=instance).delete() if disp['type'] == 'work': work_data = disp['work'] work_data['project'] = instance work_sr = WorkSerializer(data=work_data, context=self.context) work = work_sr.create(work_data) if disp['type'] == 'job': job_data = disp['job'] job_data['project'] = instance job_sr = JobSerializer(data=job_data, context=self.context) job = job_sr.create(job_data) # Associate causes if causes: instance.causes.remove(*core_models.Cause.objects.filter( channel__slug=self.context["request"].channel)) for cause in causes: c = core_models.Cause.objects.get(pk=cause['id']) instance.causes.add(c) # Associate categories if categories: instance.categories.remove(*core_models.Category.objects.filter( channel__slug=self.context["request"].channel)) for category in categories: c = models.Category.objects.get(pk=category['id']) instance.categories.add(c) # Associate skills if skills: instance.skills.remove(*core_models.Skill.objects.filter( channel__slug=self.context["request"].channel)) for skill in skills: s = core_models.Skill.objects.get(pk=skill['id']) instance.skills.add(s) # Associate galleries if galleries: instance.galleries.remove(*Gallery.objects.filter( channel__slug=self.context["request"].channel)) for gallery in galleries: g = Gallery.objects.get(pk=gallery['id']) instance.galleries.add(g) # Associate documents if documents: instance.documents.remove(*UploadedDocument.objects.filter( channel__slug=self.context["request"].channel)) for document in documents: d = UploadedDocument.objects.get(pk=document['id']) instance.documents.add(d) return super(ProjectCreateUpdateSerializer, self).update(instance, validated_data) @add_disponibility_representation def to_representation(self, instance): return super(ProjectCreateUpdateSerializer, self).to_representation(instance)
class FullCauseSerializer(ChannelRelationshipSerializer): image = UploadedImageSerializer() class Meta: fields = ['id', 'name', 'slug', 'image'] model = models.Cause
class ShortUserPublicRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() class Meta: model = models.User fields = ['uuid', 'name', 'avatar', 'slug']
class UserProjectRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() class Meta: model = models.User fields = ['uuid', 'name', 'avatar', 'email', 'phone', 'phone2', 'slug']
class OrganizationCreateSerializer(ChannelRelationshipSerializer): address = address_serializers[0](required=False) causes = CauseAssociationSerializer(many=True, required=False) image = UploadedImageSerializer(required=False) image_id = serializers.IntegerField(required=False) galleries = GalleryAssociationSerializer(many=True, required=False) class Meta: model = models.Organization fields = ['id', 'slug', 'owner', 'document', 'name', 'website', 'facebook_page', 'address', 'details', 'description', 'type', 'image', 'image_id', 'cover', 'hidden_address', 'causes', 'contact_name', 'contact_email', 'contact_phone', 'benefited_people', 'galleries'] def create(self, validated_data): causes = validated_data.pop('causes', []) galleries = validated_data.pop('galleries', []) address_data = validated_data.pop('address', None) # Address if address_data: address_sr = address_serializers[0](data=address_data, context=self.context) address = address_sr.create(address_data) validated_data['address'] = address # Organization organization = super(OrganizationCreateSerializer, self).create(validated_data) # Associate causes for cause in causes: c = Cause.objects.get(pk=cause['id']) organization.causes.add(c) # Associate galleries for gallery in galleries: c = Gallery.objects.get(pk=gallery['id']) organization.galleries.add(c) return organization def update(self, instance, validated_data): causes = validated_data.pop('causes', []) galleries = validated_data.pop('galleries', []) address_data = validated_data.pop('address', None) # Iterate and save fields as drf default info = model_meta.get_field_info(instance) for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: field = getattr(instance, attr) field.set(value) else: setattr(instance, attr, value) # Save related resources if address_data: address_sr = address_serializers[0](data=address_data, context=self.context) address = address_sr.create(address_data) instance.address = address # Associate causes if causes: instance.causes.remove(*Cause.objects.filter(channel__slug=self.context["request"].channel)) for cause in causes: c = Cause.objects.get(pk=cause['id']) instance.causes.add(c) # Associate galleries if galleries: instance.galleries.remove(*Gallery.objects.filter(channel__slug=self.context["request"].channel)) for gallery in galleries: g = Gallery.objects.get(pk=gallery['id']) instance.galleries.add(g) instance.save() return instance
class OrganizationInviteUserPublicRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() class Meta: model = User fields = ['uuid', 'name', 'email', 'avatar', 'slug']
class MemberListRetrieveSerializer(ChannelRelationshipSerializer): avatar = UploadedImageSerializer() class Meta: model = User fields = ['id', 'uuid', 'name', 'email', 'avatar', 'slug']