def post(self, request): try: user_profile = UserProfile.objects.get(user=self.request.user) except UserProfile.DoesNotExist: raise NotFound('User not found.') user = user_profile.user if 'first_name' in request.data: user.first_name = request.data['first_name'] if 'last_name' in request.data: user.last_name = request.data['last_name'] user_profile.name = user.first_name + ' ' + user.last_name user_profile.url_slug = (user.first_name + user.last_name).lower() + str(user.id) user.save() if 'image' in request.data: user_profile.image = get_image_from_data_url( request.data['image'])[0] if 'thumbnail_image' in request.data: user_profile.thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] if 'background_image' in request.data: user_profile.background_image = get_image_from_data_url( request.data['background_image'], True, 1280)[0] if 'location' in request.data: geo_location = get_location(request.data['location']) user_profile.location = geo_location if 'biography' in request.data: user_profile.biography = request.data['biography'] if 'website' in request.data: user_profile.website = request.data['website'] if 'availability' in request.data: try: availability = Availability.objects.get( id=int(request.data['availability'])) except Availability.DoesNotExist: raise NotFound('Availability not found.') user_profile.availability = availability if 'skills' in request.data: for skill in user_profile.skills.all(): if not skill.id in request.data['skills']: user_profile.skills.remove(skill) for skill_id in request.data['skills']: try: skill = Skill.objects.get(id=int(skill_id)) user_profile.skills.add(skill) except Skill.DoesNotExist: logger.error("Passed skill id {} does not exists") user_profile.save() serializer = UserProfileSerializer(user_profile) return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request): required_params = [ 'email', 'password', 'first_name', 'last_name', 'location', 'send_newsletter', ] for param in required_params: if param not in request.data: raise ValidationError('Required parameter is missing') if User.objects.filter(username=request.data['email']).exists(): raise ValidationError("Email already in use.") location = get_location(request.data['location']) user = User.objects.create(username=request.data['email'], email=request.data['email'], first_name=request.data['first_name'], last_name=request.data['last_name'], is_active=True) user.set_password(request.data['password']) user.save() url_slug = (user.first_name + user.last_name).lower() + str(user.id) # Get location user_profile = UserProfile.objects.create( user=user, location=location, url_slug=url_slug, name=request.data['first_name'] + " " + request.data['last_name'], verification_key=uuid.uuid4(), send_newsletter=request.data['send_newsletter']) if "from_tutorial" in request.data: user_profile.from_tutorial = request.data['from_tutorial'] if "is_activist" in request.data: user_profile.is_activist = request.data['is_activist'] if "last_completed_tutorial_step" in request.data: user_profile.last_completed_tutorial_step = request.data[ 'last_completed_tutorial_step'] if settings.AUTO_VERIFY == True: user_profile.is_profile_verified = True message = "Congratulations! Your account has been created" else: send_user_verification_email(user, user_profile.verification_key) message = "You're almost done! We have sent an email with a confirmation link to {}. Finish creating your account by clicking the link.".format( user.email) # NOQA user_profile.save() return Response({'success': message}, status=status.HTTP_201_CREATED)
def create_new_project(data: Dict) -> Project: project = Project.objects.create( name=data['name'], short_description=data['short_description'], collaborators_welcome=data['collaborators_welcome'], status_id=data['status']) # Add all non required parameters if they exists in the request. if 'start_date' in data: project.start_date = data['start_date'] if 'loc' in data: location = get_location(data['loc']) project.loc = location if 'country' in data: project.country = data['country'] if 'city' in data: project.city = data['city'] if 'image' in data: project.image = get_image_from_data_url(data['image'])[0] if 'thumbnail_image' in data: project.thumbnail_image = get_image_from_data_url( data['thumbnail_image'])[0] if 'description' in data: project.description = data['description'] if 'end_date' in data: project.end_date = data['end_date'] if 'helpful_connections' in data: project.helpful_connections = data['helpful_connections'] if 'is_draft' in data: project.is_draft = data['is_draft'] if 'website' in data: project.website = data['website'] project.url_slug = project.name.replace(" ", "") + str(project.id) if 'skills' in data: for skill_id in data['skills']: try: skill = Skill.objects.get(id=int(skill_id)) project.skills.add(skill) except Skill.DoesNotExist: logger.error( "Passed skill ID {} does not exists".format(skill_id)) continue project.save() return project
def add_additional_create_idea_params(idea: Idea, data: dict, url_slug: str) -> None: idea.url_slug = url_slug try: hub = Hub.objects.get(url_slug=data['hub']) hub_shared_in = Hub.objects.get(url_slug=data['hub_shared_in']) except Hub.DoesNotExist: idea.delete() raise ValidationError('Hub does not exist: ' + data['hub']) idea.hub = hub idea.hub_shared_in = hub_shared_in if 'location' in data: idea.location = get_location(data['location']) if 'image' in data and 'thumbnail_image' in data: idea.image = get_image_from_data_url(data['image'])[0] idea.thumbnail_image = get_image_from_data_url( data['thumbnail_image'])[0] if 'parent_organization' in data: try: organization = Organization.objects.get( id=data['parent_organization']) except Organization.DoesNotExist: idea.delete() raise ValidationError('Organization does not exist!') idea.organization = organization try: idea.save() except IntegrityError: if url_slug.endswith(str(idea.id)): # It seems like we alread called this function and added the id to the url slug, but there is still an integrity error! # Seems like it is unrelated to the url_slug and there is some bigger problem idea.delete() raise ValidationError("Internal Server Error") else: # The url slug is already taken! We'll append the project id in the end to make it unique again add_additional_create_idea_params(idea, data, url_slug + str(idea.id))
def patch(self, request, url_slug, format=None): try: project = Project.objects.get(url_slug=url_slug) except Project.DoesNotExist: return Response({'message': 'Project not found: {}'.format(url_slug)}, status=status.HTTP_404_NOT_FOUND) # Author: Dip # Code formatting here. So fields are just pass through so combing them and using setattr method insted. pass_through_params = ['collaborators_welcome', 'description', 'helpful_connections','short_description', 'website'] for param in pass_through_params: if param in request.data: setattr(project, param, request.data[param]) if 'name' in request.data and request.data['name'] != project.name: project.name = request.data['name'] project.url_slug = request.data['name'] + str(project.id) if 'skills' in request.data: for skill in project.skills.all(): if not skill.id in request.data['skills']: logger.error("this skill needs to be deleted: "+skill.name) project.skills.remove(skill) for skill_id in request.data['skills']: try: skill = Skill.objects.get(id=skill_id) project.skills.add(skill) except Skill.DoesNotExist: logger.error("Passed skill id {} does not exists") old_project_taggings = ProjectTagging.objects.filter(project=project) old_project_tags = old_project_taggings.values('project_tag') if 'project_tags' in request.data: order = len(request.data['project_tags']) for tag in old_project_tags: if not tag['project_tag'] in request.data['project_tags']: tag_to_delete = ProjectTags.objects.get(id=tag['project_tag']) ProjectTagging.objects.filter(project=project, project_tag=tag_to_delete).delete() for tag_id in request.data['project_tags']: old_taggings = old_project_taggings.filter(project_tag=tag_id) if not old_taggings.exists(): try: tag = ProjectTags.objects.get(id=tag_id) ProjectTagging.objects.create( project_tag=tag, project=project, order = order ) except ProjectTags.DoesNotExist: logger.error("Passed proj tag id {} does not exists") else: old_tagging = old_taggings[0] if not old_tagging.order == order: old_tagging.order = int(order) old_tagging.save() order = order - 1 if 'image' in request.data: project.image = get_image_from_data_url(request.data['image'])[0] if 'thumbnail_image' in request.data: project.thumbnail_image = get_image_from_data_url(request.data['thumbnail_image'])[0] if 'status' in request.data: try: project_status = ProjectStatus.objects.get(id=int(request.data['status'])) except ProjectStatus.DoesNotExist: raise NotFound('Project status not found.') project.status = project_status if 'start_date' in request.data: project.start_date = parse(request.data['start_date']) if 'end_date' in request.data: project.end_date = parse(request.data['end_date']) if 'location' in request.data: project.location = request.data['location'] if 'loc' in request.data: location = get_location(request.data['loc']) project.loc = location if 'is_draft' in request.data: project.is_draft = False if 'is_personal_project' in request.data: if request.data['is_personal_project'] == True: project_parents = ProjectParents.objects.get(project=project) project_parents.parent_organization = None project_parents.save() if 'parent_organization' in request.data: project_parents = ProjectParents.objects.get(project=project) try: organization = Organization.objects.get(id=request.data['parent_organization']) except Organization.DoesNotExist: organization = None logger.error("Passed parent organization id {} does not exist") project_parents.parent_organization = organization project_parents.save() project.save() return Response({ 'message': 'Project {} successfully updated'.format(project.name), 'url_slug': project.url_slug }, status=status.HTTP_200_OK)
def patch(self, request, url_slug, format=None): try: organization = Organization.objects.get(url_slug=str(url_slug)) except Organization.DoesNotExist: return Response( {'message': 'Organization not found: {}'.format(url_slug)}, status=status.HTTP_404_NOT_FOUND) pass_through_params = [ 'name', 'short_description', 'school', 'organ', 'website' ] for param in pass_through_params: if param in request.data: setattr(organization, param, request.data[param]) if 'location' in request.data: organization.location = get_location(request.data['location']) if 'image' in request.data: organization.image = get_image_from_data_url( request.data['image'])[0] if 'thumbnail_image' in request.data: organization.thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] if 'background_image' in request.data: organization.background_image = get_image_from_data_url( request.data['background_image'])[0] if 'parent_organization' in request.data: if 'has_parent_organization' in request.data and request.data[ 'has_parent_organization'] == False: organization.parent_organization = None else: try: parent_organization = Organization.objects.get( id=request.data['parent_organization']) except Organization.DoesNotExist: return Response( { 'message': 'Parent org not found for organization {}'.format( url_slug) }, status=status.HTTP_404_NOT_FOUND) organization.parent_organization = parent_organization old_organization_taggings = OrganizationTagging.objects.filter( organization=organization).values('organization_tag') if 'types' in request.data: for tag in old_organization_taggings: if not tag['organization_tag'] in request.data['types']: tag_to_delete = OrganizationTags.objects.get( id=tag['organization_tag']) OrganizationTagging.objects.filter( organization=organization, organization_tag=tag_to_delete).delete() for tag_id in request.data['types']: if not old_organization_taggings.filter( organization_tag=tag_id).exists(): try: tag = OrganizationTags.objects.get(id=tag_id) OrganizationTagging.objects.create( organization_tag=tag, organization=organization) except OrganizationTags.DoesNotExist: logger.error("Passed org tag id {} does not exists") organization.save() return Response({'message': 'Successfully updated organization.'}, status=status.HTTP_200_OK)
def post(self, request): required_params = [ 'name', 'team_members', 'location', 'image', 'organization_tags' ] for param in required_params: if param not in request.data: return Response( { 'message': 'Required parameter missing: {}'.format(param) }, status=status.HTTP_400_BAD_REQUEST) organization, created = Organization.objects.get_or_create( name=request.data['name']) if created: organization.url_slug = organization.name.replace(" ", "") + str( organization.id) if 'image' in request.data: organization.image = get_image_from_data_url( request.data['image'])[0] if 'thumbnail_image' in request.data: organization.thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] if 'background_image' in request.data: organization.background_image = get_image_from_data_url( request.data['background_image'])[0] if 'parent_organization' in request.data: try: parent_org = Organization.objects.get( id=int(request.data['parent_organization'])) except Organization.DoesNotExist: return Response( {'message': 'Parent organization not found.'}, status=status.HTTP_404_NOT_FOUND) organization.parent_organization = parent_org # Get accurate location from google maps. if 'location' in request.data: organization.location = get_location(request.data['location']) if 'short_description' in request.data: organization.short_description = request.data[ 'short_description'] if 'website' in request.data: organization.website = request.data['website'] organization.save() roles = Role.objects.all() for member in request.data['team_members']: user_role = roles.filter( id=int(member['permission_type_id'])).first() try: user = User.objects.get(id=int(member['user_id'])) except User.DoesNotExist: logger.error("Passed user id {} does not exists".format( member['user_id'])) continue if user: OrganizationMember.objects.create( user=user, organization=organization, role=user_role) logger.info("Organization member created {}".format( user.id)) if 'organization_tags' in request.data: for organization_tag_id in request.data['organization_tags']: try: organization_tag = OrganizationTags.objects.get( id=int(organization_tag_id)) except OrganizationTags.DoesNotExist: logger.error( "Passed organization tag ID {} does not exists". format(organization_tag_id)) continue if organization_tag: OrganizationTagging.objects.create( organization=organization, organization_tag=organization_tag) logger.info( "Organization tagging created for organization {}". format(organization.id)) return Response( { 'message': 'Organization {} successfully created'.format( organization.name), 'url_slug': organization.url_slug }, status=status.HTTP_201_CREATED) else: return Response( { 'message': 'Organization with name {} already exists'.format( request.data['name']) }, status=status.HTTP_400_BAD_REQUEST)
def migrate_table(name, num_elements, elements, location_key, unknown_location): print("Total {name} to migrate to new location system: {number}".format( name=name, number=num_elements)) counter = 0 for element in elements: print("City:" + str(element.city) + " country:" + str(element.country)) locations = Location.objects.filter(city=element.city, country=element.country) if locations.exists() and locations[0].is_formatted == True: print("it exists and is formatted!") setattr(element, location_key, locations[0]) element.save() elif element.city == None or element.country == None: setattr(element, location_key, unknown_location) print( "no city and country. assigning unknown location to element " + str(element.url_slug)) element.save() else: url_root = settings.LOCATION_SERVICE_BASE_URL + "/search?q=" url_ending = "&format=json&addressdetails=1&polygon_geojson=1&polygon_threshold=0.01&accept-language=en-US,en;q=0.9" query = element.city + ", " + element.country url = url_root + query + url_ending response = requests.get(url) location_results = get_location_results(response.text) if (len(location_results) == 0): setattr(element, location_key, unknown_location) print("assigning unknown location for user " + element.url_slug) element.save() else: location_object = location_results[0] location = get_location(location_object) if location.is_formatted == False: print(location) print("formatting location " + location_object['name']) if not location_object['type'] == "Point": multipolygon = get_multipolygon_from_geojson( location_object['geojson']) location.multi_polygon = multipolygon location.city = location_object['city'] location.country = location_object['country'] location.state = location_object['state'] location.name = location_object['name'] location.is_formatted = True location.centre_point = Point( float(location_object['lat']), float(location_object['lon'])) location.save() print("assigning location:" + location_object['name'] + " for user " + element.url_slug) setattr(element, location_key, location) element.save() counter = counter + 1 print("{counter}/{total} {name} updated ({percentage}%)".format( counter=counter, total=num_elements, name=name, percentage=int((counter / num_elements) * 100))) print("Total {name} updated: {counter}".format(name=name, counter=counter))
def patch(self, request, url_slug, format=None): try: organization = Organization.objects.get(url_slug=str(url_slug)) except Organization.DoesNotExist: return Response( {'message': _('Organization not found:') + url_slug}, status=status.HTTP_404_NOT_FOUND) pass_through_params = [ 'name', 'short_description', 'about', 'school', 'organ', 'website', 'organization_size' ] for param in pass_through_params: if param in request.data: setattr(organization, param, request.data[param]) if 'location' in request.data: organization.location = get_location(request.data['location']) if 'language' in request.data: language = Language.objects.filter( language_code=request.data['language']) if language.exists(): organization.language = language[0] if 'image' in request.data: organization.image = get_image_from_data_url( request.data['image'])[0] if 'thumbnail_image' in request.data: organization.thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] if 'background_image' in request.data: organization.background_image = get_image_from_data_url( request.data['background_image'])[0] if 'hubs' in request.data: for hub in organization.hubs.all(): if not hub.url_slug in request.data['hubs']: organization.hubs.remove(hub) for hub_url_slug in request.data['hubs']: try: hub = Hub.objects.get(url_slug=hub_url_slug) organization.hubs.add(hub) except Hub.DoesNotExist: logger.error("Passed hub url_slug {} does not exists") if 'parent_organization' in request.data: if 'has_parent_organization' in request.data \ and request.data['has_parent_organization'] == False: organization.parent_organization = None else: try: parent_organization = Organization.objects.get( id=request.data['parent_organization']) except Organization.DoesNotExist: return Response( { 'message': _('Parent organization not found for organization') + url_slug }, status=status.HTTP_404_NOT_FOUND) organization.parent_organization = parent_organization items_to_translate = [{ 'key': 'name', 'translation_key': 'name_translation' }, { 'key': 'short_description', 'translation_key': 'short_description_translation' }, { 'key': 'about', 'translation_key': 'about_translation' }, { 'key': 'school', 'translation_key': 'school_translation' }, { 'key': 'organ', 'translation_key': 'organ_translation' }] edit_translations(items_to_translate, request.data, organization, "organization") old_organization_taggings = OrganizationTagging.objects.filter( organization=organization).values('organization_tag') if 'types' in request.data: for tag in old_organization_taggings: if not tag['organization_tag'] in request.data['types']: tag_to_delete = OrganizationTags.objects.get( id=tag['organization_tag']) OrganizationTagging.objects.filter( organization=organization, organization_tag=tag_to_delete).delete() for tag_id in request.data['types']: if not old_organization_taggings.filter( organization_tag=tag_id).exists(): try: tag = OrganizationTags.objects.get(id=tag_id) OrganizationTagging.objects.create( organization_tag=tag, organization=organization) except OrganizationTags.DoesNotExist: logger.error( _("Passed organization tag id does not exists: ") + tag_id) organization.save() return Response({'message': _('Successfully updated organization.')}, status=status.HTTP_200_OK)
def post(self, request): required_params = [ 'name', 'team_members', 'location', 'image', 'organization_tags', 'translations', 'source_language', 'short_description' ] for param in required_params: if param not in request.data: return Response( { 'message': 'Required parameter missing: {}'.format(param) }, status=status.HTTP_400_BAD_REQUEST) texts = {"name": request.data['name']} if 'short_description' in request.data: texts['short_description'] = request.data['short_description'] if 'about' in request.data: texts['about'] = request.data['about'] try: translations = get_translations(texts, request.data['translations'], request.data['source_language'], ["name"]) except ValueError as ve: translations = None logger.error( "TranslationFailed: Error translating texts, {}".format(ve)) organization, created = Organization.objects.get_or_create( name=request.data['name']) if created: organization.url_slug = organization.name.replace(" ", "") + str( organization.id) # Add primary language to organization table. source_language = Language.objects.get( language_code=request.data['source_language']) organization.language = source_language if 'image' in request.data: organization.image = get_image_from_data_url( request.data['image'])[0] if 'thumbnail_image' in request.data: organization.thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] if 'background_image' in request.data: organization.background_image = get_image_from_data_url( request.data['background_image'])[0] if 'parent_organization' in request.data: try: parent_org = Organization.objects.get( id=int(request.data['parent_organization'])) except Organization.DoesNotExist: return Response( {'message': 'Parent organization not found.'}, status=status.HTTP_404_NOT_FOUND) organization.parent_organization = parent_org # Get accurate location from google maps. if 'location' in request.data: organization.location = get_location(request.data['location']) if 'short_description' in request.data: organization.short_description = request.data[ 'short_description'] if 'about' in request.data: organization.about = request.data['about'] if 'website' in request.data: organization.website = request.data['website'] if 'organization_size' in request.data and is_valid_organization_size( request.data['organization_size']): organization.organization_size = request.data[ 'organization_size'] if 'hubs' in request.data: hubs = [] for hub_url_slug in request.data['hubs']: try: hub = Hub.objects.get(url_slug=hub_url_slug) hubs.append(hub) except Hub.DoesNotExist: logger.error("Passed hub url_slug {} does not exists") organization.hubs.set(hubs) organization.save() # Create organization translation if translations: for key in translations['translations']: if not key == "is_manual_translation": language_code = key texts = translations['translations'][language_code] language = Language.objects.get( language_code=language_code) if language_code in request.data['translations']: is_manual_translation = request.data[ 'translations'][language_code][ 'is_manual_translation'] else: is_manual_translation = False create_organization_translation( organization, language, texts, is_manual_translation) roles = Role.objects.all() for member in request.data['team_members']: user_role = roles.filter( id=int(member['permission_type_id'])).first() try: user = User.objects.get(id=int(member['user_id'])) except User.DoesNotExist: logger.error("Passed user id {} does not exists".format( member['user_id'])) continue if user: OrganizationMember.objects.create( user=user, organization=organization, role=user_role) logger.info("Organization member created {}".format( user.id)) if 'organization_tags' in request.data: for organization_tag_id in request.data['organization_tags']: try: organization_tag = OrganizationTags.objects.get( id=int(organization_tag_id)) except OrganizationTags.DoesNotExist: logger.error( "Passed organization tag ID {} does not exists". format(organization_tag_id)) continue if organization_tag: OrganizationTagging.objects.create( organization=organization, organization_tag=organization_tag) logger.info( "Organization tagging created for organization {}". format(organization.id)) return Response( { 'message': 'Organization {} successfully created'.format( organization.name), 'url_slug': organization.url_slug }, status=status.HTTP_201_CREATED) else: return Response( { 'message': 'Organization with name {} already exists'.format( request.data['name']) }, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, url_slug, format=None): idea = verify_idea(url_slug) if not idea: return Response({'message': 'Idea not found'}, status=status.HTTP_404_NOT_FOUND) if 'name' in request.data and idea.name != request.data['name']: idea.name = request.data['name'] if 'short_description' in request.data and\ idea.short_description != request.data['short_description']: idea.short_description = request.data['short_description'] if 'image' in request.data and request.data['image'] is not None: image = get_image_from_data_url(request.data['image'])[0] idea.image = image if 'thumbnail_image' in request.data and request.data[ 'thumbnail_image']: thumbnail_image = get_image_from_data_url( request.data['thumbnail_image'])[0] idea.thumbnail_image = thumbnail_image if 'location' in request.data and request.data['location']: idea.location = get_location(request.data['location']) if 'hub' in request.data: try: hub = Hub.objects.get(url_slug=request.data['hub']) except Hub.DoesNotExist: hub = None if hub: idea.hub = hub if 'parent_organization' in request.data: try: organization = Organization.objects.get( id=request.data['parent_organization']) except Organization.DoesNotExist: organization = None if organization: idea.organization = organization idea.save() # TODO (Dip 8-6-2021): Transfer this logic to celery task. texts = { "name": idea.name, "short_description": idea.short_description } try: translations = get_translations(texts, {}, idea.language.language_code) except ValueError as ve: translations = None logger.error( "TranslationFailed: Error translating texts, {}".format(ve)) if translations: idea_translations(idea=idea, translations=translations['translations'], source_language=idea.language) serializer = IdeaSerializer(idea) return Response(serializer.data, status=status.HTTP_200_OK)