def delete_comment(request, comment_id): try: comment = Comment.objects.get(pk=comment_id) # TODO(Varun): Same logic as duplicated from template generation to show # delete button from interactions.CommentUtilities import CommentUtilities (host_type, host, root) = CommentUtilities.get_comment_root(comment) if host_type.name == 'project': if request.user == comment.user or request.user in host.admins.all(): # Delete all descendant elements of this comment. delete_comment_tree(comment) return APIUtilities._api_success() else: return APIUtilities._api_unauthorized_failure() elif host_type.name == 'resource': if request.user == comment.user or ( request.user in host.collaborators.all() or request.user == host.creator): delete_comment_tree(comment) return APIUtilities._api_success() return APIUtilities._api_failure() except Comment.DoesNotExist: return APIUtilities._api_not_found()
def get_favorite_state(request, favorite_type, parent_id): try: from oer.models import Resource, Collection from django.contrib.contenttypes.models import ContentType resource_ct = ContentType.objects.get_for_model(Resource) collection_ct = ContentType.objects.get_for_model(Collection) favorite = Favorite.objects.get( user=request.user, parent_id=parent_id, parent_type=( resource_ct if favorite_type == 'resource' else collection_ct)) context = { 'favorite': { 'state': 'true', 'created': str(favorite.created) } } return APIUtilities._api_success(context) except: context = { 'favorite': { 'state': 'false' } } return APIUtilities._api_success(context)
def cast_vote(request, comment_id, positive): comment_ct = ContentType.objects.get_for_model(Comment) # Check if the comment already exists try: existing_vote = Vote.objects.get( parent_id=comment_id, parent_type=comment_ct, positive=positive, user=request.user ) existing_vote.delete() response = {'status': 'unvote success'} return HttpResponse( json.dumps(response), 200, content_type="application/json") except Vote.DoesNotExist: try: comment = Comment.objects.get(pk=comment_id) # Create the vote and save it new_vote = Vote() new_vote.user = request.user new_vote.positive = positive new_vote.parent = comment new_vote.save() if positive: # Send out a notification to the person who originally wrote # the comment, if a positive vote is casted. Vote.vote_casted.send(sender="Comments", vote=new_vote) return APIUtilities._api_success() except: return APIUtilities._api_failure()
def reposition_cover_picture(request, project_id): try: project = Project.objects.get(pk=project_id) except: raise Http404 if request.user not in project.admins.all(): return APIUtilities._api_unauthorized_failure() left = request.GET.get('left', None) top = request.GET.get('top', None) try: project.cover_pic_position.top = int(top) project.cover_pic_position.left = int(left) project.cover_pic_position.save() return APIUtilities._api_success() except: context = { 'title': 'Cannot reposition project cover picture.', 'message': 'We failed to reposition the project cover picture. Please ' + 'contact us if this problem persists.' } return APIUtilities._api_failure(context)
def get_resource_vote_count(request, resource_id): try: from oer.models import Resource resource = Resource.objects.get(pk=resource_id) except: return APIUtilities._api_not_found() try: from django.contrib.contenttypes.models import ContentType resource_ct = ContentType.objects.get_for_model(Resource) upvotes = Vote.objects.filter( parent_id=resource.id, parent_type=resource_ct, positive=1) downvotes = Vote.objects.filter( parent_id=resource.id, parent_type=resource_ct, positive=0) user_upvoted = False user_downvoted = False if (request.user.is_authenticated()): if upvotes.filter(user=request.user).count() > 0: user_upvoted = True if downvotes.filter(user=request.user).count() > 0: user_downvoted = True context = { 'upvote_count': upvotes.count(), 'downvote_count': downvotes.count(), 'user_upvoted': 'true' if user_upvoted else 'false', 'user_downvoted': 'true' if user_downvoted else 'false' } return APIUtilities._api_success(context) except: return APIUtilities._api_failure()
def get_standard(request, category_id): from meta.models import Category category = Category.objects.get(pk=category_id) # Get all categories in this standard. subjects = Category.objects.filter(parent=category) # Get all the subcategories in the currently selected subject. grades = Category.objects.filter(parent=subjects[0]).order_by('position') context = { 'subjects': [], 'grades': [], } for subject in subjects: context['subjects'].append({ 'title': subject.title, 'id': subject.id }) for grade in grades: context['grades'].append({ 'title': grade.title, 'id': grade.id }) return APIUtilities._api_success(context)
def load(self): category = Category.objects.get(pk=self.current_category_id) all_raw_resources = [] all_resources = [] category_resources = Resource.objects.filter(categories=category).order_by('-created') tagged_resources = Resource.objects.filter(tags__in=category.tags.all()).filter( tags__in=Tag.objects.filter(category=self.resource_type_tag_category)).order_by('-created') category_resource_count = category_resources.count() def categorize_resource(r): r.category = category return r if self.resource_count <= category_resource_count: all_raw_resources += list(OrderedDict.fromkeys( category_resources[(self.resource_count):] | map(categorize_resource, tagged_resources))) else: all_raw_resources += map(categorize_resource, tagged_resources[int(self.resource_count) - category_resource_count:]) for resource in all_raw_resources: try: self.build_browse_resource(resource) all_resources.append(resource) except Tag.DoesNotExist: pass serialized_resources = serialize(all_resources) context = { 'resources': serialized_resources, } return APIUtilities._api_success(context)
def get_child_tags_from_category(request, category_id): from meta.models import Category, TagCategory category = Category.objects.get(pk=category_id) # Get all tags in order that belong to this category. from meta.CategoryUtilities import TreeBuilder tag_category_builder = TreeBuilder('tag_category') (browse_tree, flattened_tree) = tag_category_builder.build_tree( {'root': [TagCategory.objects.get(title='Standards')]}, []) tags = category.tags.filter(category__in=flattened_tree).order_by('position') serialized_tags = {} for tag in tags: serialized_tags[tag.id] = { 'id': tag.id, 'title': tag.title, 'description': tag.description, 'position': tag.position, 'url': reverse( 'meta:standard', kwargs={ 'tag_title': tag.title }) } context = { 'tags': serialized_tags } return APIUtilities._api_success(context)
def get_standards(request): from meta.models import Category root_category = Category.objects.get(title='Standards') # Get all categories whose parent is root_category. child_categories = Category.objects.filter(parent=root_category).order_by( 'position') serialized_standards = {} for standard in child_categories: serialized_standards[standard.id] = { 'id': standard.id, 'title': standard.title, 'slug': standard.slug, 'position': standard.position } subjects = Category.objects.filter(parent=standard).order_by('position') serialized_subjects = {} for subject in subjects: serialized_subjects[subject.id] = { 'id': subject.id, 'title': subject.title, 'slug': subject.slug, 'position': subject.position } serialized_standards[standard.id]['subjects'] = serialized_subjects context = { 'standards': serialized_standards } return APIUtilities._api_success(context)
def request_invite(request, project_id): project = Project.objects.get(pk=project_id) try: # Check to see if the user already exists as a member. Membership.objects.get( user=request.user, project=project) context = { 'title': 'Cannot complete the request invite.', 'message': 'We failed to make a request invite on your behalf ' + 'because you either have already sent an invite request or are a ' + 'current member.' } return APIUtilities._api_failure(context) except Membership.DoesNotExist: if project.visibility != 'public': new_membership = Membership( user=request.user, project=project, confirmed=False) new_membership.save() # Create a notification for the admins about this request. Membership.new_invite_request.send( sender="Projects", membership_id=new_membership.id, request=request) else: new_membership = Membership( user=request.user, project=project, confirmed=True) new_membership.save() # Create a notification for the admins about this membership. Membership.new_member.send( sender="Projects", membership_id=new_membership.id, request=request) return APIUtilities._api_success()
def get_licenses(request): try: licenses = License.objects.all() serialized_licenses = [] for license in licenses: serialized_license = { 'id': license.id, 'title': license.title, 'description': license.description } serialized_licenses.append(serialized_license) context = { 'licenses': serialized_licenses } return APIUtilities._api_success(context) except: context = { 'title': 'Could not load the licenses list', 'message': 'We failed to load the list of standards for you. ' + 'Please contact us if the problem persists.' } return APIUtilities._api_failure(context)
def cast_resource_revision_vote(request, resource_id, revision_id, positive): try: from oer.models import Resource, ResourceRevision Resource.objects.get(pk=resource_id) revision = ResourceRevision.objects.get(pk=revision_id) except: return APIUtilities._api_not_found() # Check if the vote already exists. try: from django.contrib.contenttypes.models import ContentType resource_revision_ct = ContentType.objects.get_for_model(ResourceRevision) existing_vote = Vote.objects.get( user=request.user, parent_type=resource_revision_ct, parent_id=revision.id, positive=positive) existing_vote.delete() context = {'action': 'unvote'} return APIUtilities._api_success(context) except Vote.DoesNotExist: try: # Create the vote and save it new_vote = Vote() new_vote.user = request.user new_vote.positive = positive new_vote.parent = revision new_vote.save() if positive and revision.user != request.user: Vote.resource_revision_vote_casted.send(sender="ResourceRevision", vote=new_vote) return APIUtilities._api_success() except: context = { 'title': 'Unable to cast revision vote', 'message': 'We apologize as we failed to cast your vote on this resource revision. ' + 'Please contact us if the problem persists.' } return APIUtilities._api_failure(context)
def add_member(request, project_id, user_id): if not request.user.is_authenticated(): context = { 'title': 'You are not logged in', 'message': 'You need to be logged in to add a member to the' + 'project.' } return APIUtilities._api_failure(context) project = Project.objects.get(pk=project_id) if request.user not in project.admins.all(): context = { 'title': 'You are not the administrator', 'message': 'You must be an administrator of the project to add a' + 'member' } return APIUtilities._api_failure(context) from django.contrib.auth.models import User user = User.objects.get(pk=user_id) if Membership.objects.filter(user=user, project=project).count() != 0: context = { 'title': 'Member is already added', 'message': 'This member is already a part of the project.' } return APIUtilities._api_failure(context) try: add_user_to_project(user, project) # Prepare (serialize) user object be sent through the response. context = { 'user': { 'id': user.id, 'name': user.get_full_name(), 'username': user.username, 'profile_pic': settings.MEDIA_URL + user.get_profile().profile_pic.name, 'project_id': project.id } } return APIUtilities._api_success(context) except: context = { 'title': 'Cannot add new member', 'message': 'We failed to add this member to this project. We ' + 'apologize for the inconvenience. Visit our Help center to look ' + 'for a solution.' } return APIUtilities._api_failure(context)
def decline_request(request, request_id): try: membership_request = Membership.objects.get(pk=request_id) membership_request.delete() return APIUtilities._api_success() except: context = { 'title': 'Could not accept the request.', 'message': 'We failed to make a decline the invite request into the group ' + 'due to an internal problem. Please contact us if this problem persists.' } return APIUtilities._api_failure(context)
def remove_admin(request, project_id, user_id): if not request.user.is_authenticated(): context = { 'title': 'You are not logged in', 'message': 'You need to be logged in to remove an administrator ' + 'from the group.' } return APIUtilities._api_failure(context) project = Project.objects.get(pk=project_id) if request.user not in project.admins.all(): context = { 'title': 'You are not the administrator', 'message': 'You must be an administrator of the group to remove ' + 'another administrator' } return APIUtilities._api_failure(context) from django.contrib.auth.models import User user = User.objects.get(pk=user_id) # Check if the user being requested to be added is a current member. if user not in project.admins.all(): context = { 'title': user.username + ' is not an administrator', 'message': ('The user who you wish to remove as an administrator ' + 'is not an administrator. In order to remove %s as an ' + 'administrator, the user must first be be assigned as an ' + 'administrator') % user.username } return APIUtilities._api_failure(context) try: # Add the user to the project members. project.admins.remove(user) project.save() return APIUtilities._api_success() except: context = { 'title': 'Cannot remove the administrator', 'message': 'We failed to remove this administrator from this ' + 'project. We apologize for the inconvenience. Visit our Help ' + 'center to look for a solution.' } return APIUtilities._api_failure(context)
def list_user_favorites(request): try: from django.contrib.auth.models import User user = User.objects.get(username=request.user.username) except: return APIUtilities._api_not_found() # Get user favorites. user_favorites = Favorite.objects.filter(user=user) from django.core.urlresolvers import reverse serialized_favorites = list() for favorite in user_favorites: if favorite.parent_type.name == 'resource': url = reverse( 'read', kwargs={ 'resource_id': favorite.parent.id, 'resource_slug': favorite.parent.slug }) thumbnail = 'http://' + request.get_host( ) + settings.MEDIA_URL + favorite.parent.image.name else: url = reverse( 'user:user_folder', kwargs={ 'username': favorite.parent.creator.username, 'collection_slug': favorite.parent.slug }) thumbnail = 'http://' + request.get_host( ) + settings.STATIC_URL + 'images/folder-icon.png' serialized_favorites.append({ 'id': favorite.parent.id, 'user_url': reverse('user:user_profile', kwargs={ 'username': favorite.user.username }), 'url': url, 'title': favorite.parent.title, 'user': favorite.user.get_full_name(), 'username': favorite.user.username, 'views': favorite.parent.views, 'thumbnail': thumbnail }) context = { 'favorites': serialized_favorites } return APIUtilities._api_success(context)
def post_comment_reference(request): if request.method == "POST": try: from interactions.models import CommentReference from django.contrib.contenttypes.models import ContentType # Get comment reference owner. owner_content_type = ContentType.objects.get(pk=request.POST.get('owner_type')) # Create a comment reference to no comment. new_comment_reference = CommentReference( reference=request.POST.get('reference'), owner_id=request.POST.get('owner_id'), owner_type=owner_content_type ) new_comment_reference.save() # Create a new comment. comment_reference_content_type = ContentType.objects.get_for_model(CommentReference) modified_request = request.POST.copy() modified_request.setdefault('parent_type', comment_reference_content_type.id) modified_request.setdefault('parent_id', new_comment_reference.id) new_comment = create_comment(request, modified_request) # Map the comment to the reference. new_comment_reference.comment = new_comment new_comment_reference.save() import datetime context = { 'username': new_comment.user.username, 'name': new_comment.user.get_full_name(), 'created': datetime.datetime.strftime(new_comment.created, '%b. %d, %Y, %I:%M %P'), 'profile_pic': settings.MEDIA_URL + new_comment.user.get_profile().profile_pic.name, 'body': new_comment.body_markdown_html, 'id': new_comment.id } return APIUtilities._api_success(context) except: return APIUtilities._api_failure() else: return APIUtilities._api_failure()
def accept_request(request, request_id): try: membership_request = Membership.objects.get(pk=request_id) membership_request.confirmed = True membership_request.save() # Generate notification for user just accepted into the project to notify. Membership.invite_request_accepted.send( sender="Projects", membership_id=membership_request.id, request=request) return APIUtilities._api_success() except: context = { 'title': 'Could not accept the request.', 'message': 'We failed to make a accept the invite request into the group ' + 'due to an internal problem. Please contact us if this problem persists.' } return APIUtilities._api_failure(context)
def get_project_visibility(request, project_id): try: project = Project.objects.get(pk=project_id) if not request.user: return APIUtilities._api_unauthorized_failure() context = { 'visibility': project.visibility } return APIUtilities._api_success(context) except: context = { 'title': 'Could not get the visibility of this project.', 'message': 'We failed to retrieve the visibility of ' + 'this project. Please contact us if the problem persists.' } return APIUtilities._api_failure(context)
def get_standards_tree(request): try: standards_category = Category.objects.get(title='Standards') from meta.CategoryUtilities import TreeBuilder category_builder = TreeBuilder('category_tags') (browse_tree, flattened_tree) = category_builder.build_tree( {'root': [standards_category]}, []) tree = build_standards_navigation(browse_tree) context = { 'tree': tree } return APIUtilities._api_success(context) except: context = { 'title': 'Could not load the standards list', 'message': 'We failed to load the list of standards for you. ' + 'Please contact us if the problem persists.' } return APIUtilities._api_failure(context)
def get_nested_child_tags_from_category(request, category_id): from meta.models import Category, TagCategory category = Category.objects.get(pk=category_id) import meta.CategoryUtilities as catU (browse_tree, flattened_tree) = catU.build_child_categories( {'root': [category]}, []) tags = {} standards_categories = TagCategory.objects.filter(title__in=['Standards', 'Objectives']) for descendant_category in flattened_tree: descendant_category_tags = descendant_category.tags.filter(category__in=standards_categories).order_by('position') if descendant_category_tags.count() > 0: if descendant_category.parent == category: tags[descendant_category] = descendant_category_tags else: if descendant_category.parent not in tags: tags[descendant_category.parent] = descendant_category_tags else: tags[descendant_category.parent] |= descendant_category_tags serialized_tags = [] for tag_category, tag_set in tags.items(): for tag in tag_set: serialized_tags.append({ 'id': tag.id, 'title': tag.title, 'domain': tag_category.title, 'description': tag.description, 'position': tag.position, 'url': reverse( 'meta:standard', kwargs={ 'tag_title': tag.title }) }) context = { 'tags': serialized_tags } return APIUtilities._api_success(context)
def review_resource(request): if request.method == "POST": from django.core.urlresolvers import reverse from interactions.models import Review try: modified_request = request.POST.copy() modified_request.setdefault('user', request.user.id) comment = create_comment(request, modified_request) review = Review( comment=comment, rating=int(request.POST.get('stars', None)) ) review.save() import datetime serialized_review = { 'user_url': reverse('user:user_profile', kwargs={ 'username': comment.user.username }), 'name': str(comment.user.get_full_name()), 'username': comment.user.username, 'created': datetime.datetime.strftime(comment.created, '%b. %d, %Y, %I:%M %P'), 'profile_pic': settings.MEDIA_URL + comment.user.get_profile().profile_pic.name, 'body': comment.body_markdown_html, 'stars': review.rating } context = { 'review': serialized_review } return APIUtilities._api_success(context) except: context = { 'title': 'Unable to post your review', 'message': 'We apologize as we failed to post your highly useful review. ' + 'Please contact us if the problem persists.' } return APIUtilities._api_failure(context) else: return APIUtilities._api_not_found()
def remove_member(request, project_id, user_id): if not request.user.is_authenticated(): context = { 'title': 'You are not logged in', 'message': 'You need to be logged in to remove a member from the' + 'group.' } return APIUtilities._api_failure(context) project = Project.objects.get(pk=project_id) if request.user not in project.admins.all(): context = { 'title': 'You are not the administrator', 'message': 'You must be an administrator of the group to remove a' + 'member' } return APIUtilities._api_failure(context) from django.contrib.auth.models import User user = User.objects.get(pk=user_id) try: # Remove the user from the project members and admins. member = Membership.objects.get(user=user, project=project) member.delete() project.admins.remove(user) project.save() return APIUtilities._api_success() except: context = { 'title': 'Cannot remove the member', 'message': 'We failed to remove the member from this project. We ' + 'apologize for the inconvenience. Visit our Help center to look ' + 'for a solution.' } return APIUtilities._api_failure(context)
def favorite_resource(request, favorite_type, parent_id): # Check if the favorite already exists try: from oer.models import Resource, Collection from django.contrib.contenttypes.models import ContentType resource_ct = ContentType.objects.get_for_model(Resource) collection_ct = ContentType.objects.get_for_model(Collection) existing_favorite = Favorite.objects.get( user=request.user, parent_id=parent_id, parent_type=( resource_ct.id if favorite_type == 'resource' else collection_ct.id)) existing_favorite.delete() response = {'status': 'unfavorite success'} return HttpResponse( json.dumps(response), 200, content_type="application/json") except Favorite.DoesNotExist: try: # Create the favorite and save it new_favorite = Favorite(user=request.user, parent_id=parent_id, parent_type=( resource_ct if favorite_type == 'resource' else collection_ct)) new_favorite.save() if (favorite_type == 'resource' and new_favorite.parent.user != request.user) or ( favorite_type == 'collection' and new_favorite.parent.creator != request.user): # Send out a notification to the person who originally made # the resource. from interactions.tasks import favorite as favorite_task favoriting_task = favorite_task.delay(request.get_host(), new_favorite.id) return APIUtilities._api_success() except: return APIUtilities._api_failure() except TypeError: return APIUtilities._api_failure()
def delete_category(request, project_id, category_id): try: category = GroupCategory.objects.get(pk=category_id) project = Project.objects.get(pk=project_id) except: return APIUtilities._api_not_found() if not request.user.is_authenticated() or request.user not in project.admins.all(): context = { 'title': 'You are not authorized to delete the category', 'message': 'You need to be logged in as an administrator of the group ' + 'to remove a member from the group.' } return APIUtilities._api_unauthorized_failure(context) group_categories = GroupCategory.objects.filter(parent=project).count() if group_categories == 1: context = { 'title': 'Could not delete the only category.', 'message': 'We failed to delete the category you marked for deletion ' + 'as this is the only category in the group and you need to have atleast ' + 'one category in a group. Create another category before you delete this one.' } return APIUtilities._api_failure(context) try: # Delete all the posts in this category. Comment.objects.filter(category=category).delete() category.delete() return APIUtilities._api_success() except: context = { 'title': 'Could not delete the category.', 'message': 'We failed to delete the category of this group ' + 'due to an internal problem. Please contact us if this problem persists.' } return APIUtilities._api_failure(context)
def search(self, query): from haystack.query import SearchQuerySet current_category = Category.objects.get(pk=self.current_category_id) (browse_tree, flattened_tree) = category_util.build_child_categories( {'root': [current_category]}, []) all_resources = [] all_raw_resources = [] child_categories = Category.objects.filter(parent=current_category) # Remove the current category as this a downward searchself. current_category_in_tree = next(current for current in flattened_tree if current.id == current_category.id) flattened_tree.remove(current_category_in_tree) categories = [category.title for category in flattened_tree] categories_tags = [] for category in flattened_tree: categories_tags += category.tags.all() def set_child_category(resource, immediate_category): while True: if immediate_category in child_categories: resource.category = immediate_category return None else: immediate_category = immediate_category.parent def get_child_category_from_resource_categories(resource): for resource_category in resource.object.categories.all(): if resource_category in flattened_tree: return resource_category def set_category_on_categorized_resource(resource): a = get_child_category_from_resource_categories(resource) set_child_category(resource.object, a) return resource def categorize_resource(searched_resource): # Find the child category this is a descendant in. filtered_tags = searched_resource.object.tags.exclude( category=self.resource_type_category).exclude( category=self.resources_category) for tag in filtered_tags: if tag in categories_tags: for category in flattened_tree: if tag in category.tags.all(): immediate_category = category break set_child_category(searched_resource.object, immediate_category) return searched_resource # TODO(Varun): Rope in collection search. """if len(categories) > 0 and len(categories_tags) > 0: sqs = SearchQuerySet().filter(content_auto=query, visibility='public', categories__in=categories) | SearchQuerySet( ).filter(content_description=query, visibility='public', categories__in=categories) sqs_tags = SearchQuerySet().filter(content_auto=query, visibility='public', tags__in=categories_tags) | SearchQuerySet( ).filter(content_description=query, visibility='public', tags__in=categories_tags) all_raw_resources += sorted( set(map(set_category_on_categorized_resource, sqs) + map( categorize_resource, sqs_tags)), key=lambda searched_resource: searched_resource.object.created, reverse=True) elif len(categories) > 0: sqs_tags = SearchQuerySet().filter(content_auto=query, visibility='public', tags__in=categories_tags) | SearchQuerySet( ).filter(content_description=query, visibility='public', tags__in=categories_tags) all_raw_resources += map(set_category_on_categorized_resource, sqs_tags) elif len(categories_tags) > 0:""" sqs_title_categories = SearchQuerySet().filter(content_auto=query, visibility='public', categories__in=categories) sqs_description_categories = SearchQuerySet( ).filter(content_description=query, visibility='public', categories__in=categories) sqs = set() if len(sqs_title_categories) > 0: sqs |= set(sqs_title_categories) if len(sqs_description_categories) > 0: sqs |= set(sqs_description_categories) all_raw_resources += list(map(set_category_on_categorized_resource, sqs)) # Setup each resource's favorites count and type. from meta.models import Tag for resource in all_raw_resources: try: self.build_browse_resource(resource.object) all_resources.append(resource) except Tag.DoesNotExist: pass unserialized_resources = [] for resource in all_resources: unserialized_resources.append(resource.object) serialized_resources = serialize(unserialized_resources) context = { 'resources': serialized_resources } return APIUtilities._api_success(context)
def add_admin(request, project_id, user_id): if not request.user.is_authenticated(): context = { 'title': 'You are not logged in', 'message': 'You need to be logged in to add an administrator to ' + 'the group.' } return APIUtilities._api_failure(context) project = Project.objects.get(pk=project_id) if request.user not in project.admins.all(): context = { 'title': 'You are not the administrator', 'message': 'You must be an administrator of the group to add an' + 'administrator' } return APIUtilities._api_failure(context) from django.contrib.auth.models import User user = User.objects.get(pk=user_id) # Check if the user being requested to be added is a current member. if user not in project.members.all(): context = { 'title': user.username + ' is not a member', 'message': ('The user who you wish to make an administrator is not' + 'member. In order to make %s an administrator, the user must' + 'first be added to the project as a member') % user.username } return APIUtilities._api_failure(context) try: # Add the user to the project members. project.admins.add(user) project.save() # Notify the member about being assigned an admin. Membership.member_turned_admin.send( sender="Projects", project=project, user=user, request=request) # Prepare (serialize) user object be sent through the response. context = { 'user': { 'id': user.id, 'name': user.get_full_name(), 'username': user.username, 'profile_pic': user.get_profile().profile_pic.name } } return APIUtilities._api_success(context) except: context = { 'title': 'Cannot add new administrator', 'message': 'We failed to add this administrator to this group. ' + 'We apologize for the inconvenience. Visit our Help center to ' + 'look for a solution.' } return APIUtilities._api_failure(context)