def homepage_project_json(request, project, can_edit): the_json = {} the_json['id'] = project.id the_json['title'] = project.title the_json['url'] = project.get_absolute_url() participants = project.attribution_list() the_json['authors'] = [{ 'name': get_public_name(u, request), 'last': idx == (len(participants) - 1) } for idx, u in enumerate(participants)] the_json['modified'] = project.modified.strftime("%m/%d/%y %I:%M %p") the_json['status'] = project.status() the_json['editable'] = can_edit feedback = project.feedback_discussion() if feedback: the_json['feedback'] = feedback.id parent_assignment = project.assignment() if parent_assignment: the_json['collaboration'] = {} the_json['collaboration']['title'] = parent_assignment.title the_json['collaboration']['url'] = parent_assignment.get_absolute_url() return the_json
def all_responses(self, request, project): ctx = [] responses = project.responses(request.course, request.user) for response in responses: submitted = '' if response.is_submitted(): submitted = response.date_submitted.strftime(self.date_fmt) obj = { 'url': response.get_absolute_url(), 'title': response.title, 'submitted': submitted, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': []} last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last}) ctx.append(obj) return sorted( ctx, key=lambda response: response['attribution_list'][0]['name'])
def project_json(request,project): #bad language, we should change this to user_of_assets or something space_viewer = request.user if request.GET.has_key('as') and request.user.is_staff: space_viewer = get_object_or_404(User, username=request.GET['as']) rand = ''.join([choice(letters) for i in range(5)]) data = {'project':{'title':project.title, 'body':project.body, 'participants':[{'name':p.get_full_name(), 'username':p.username, 'public_name': get_public_name(p, request), 'is_viewer': space_viewer.username == p.username, } for p in project.participants.all()], 'id':project.pk, 'url':project.get_absolute_url(), 'username':request.user.username, }, 'assets':dict([('%s_%s' % (rand,ann.asset.pk), ann.asset.sherd_json(request) ) for ann in project.citations() if ann.title != "Annotation Deleted" ]), 'annotations':[ann.sherd_json(request, rand, ('title','author') ) for ann in project.citations() ], 'type':'project', } return HttpResponse(simplejson.dumps(data, indent=2), mimetype='application/json')
def all_responses(self, request, project): ctx = [] responses = project.responses(request.course, request.user) for response in responses: submitted = '' if response.is_submitted(): submitted = response.date_submitted.strftime(self.date_fmt) obj = { 'url': response.get_absolute_url(), 'title': response.title, 'submitted': submitted, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': [] } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last }) ctx.append(obj) return sorted( ctx, key=lambda response: response['attribution_list'][0]['name'])
def dehydrate(self, bundle): bundle.data["is_assignment"] = bundle.obj.visibility_short() == "Assignment" bundle.data["is_response"] = bundle.obj.assignment() is not None bundle.data["attribution"] = bundle.obj.attribution() bundle.data["url"] = bundle.obj.get_absolute_url() bundle.data["due_date"] = bundle.obj.get_due_date() bundle.data["modified_date"] = bundle.obj.modified.strftime("%m/%d/%y") bundle.data["modified_time"] = bundle.obj.modified.strftime("%I:%M %p") bundle.data["editable"] = self.editable bundle.data["is_faculty"] = self.is_viewer_faculty participants = bundle.obj.attribution_list() bundle.data["participants"] = [ { "name": p.get_full_name(), "username": p.username, "public_name": get_public_name(p, bundle.request), "is_viewer": self.record_viewer == p.username, "last": idx == (len(participants) - 1), } for idx, p in enumerate(participants) ] bundle.data["status"] = bundle.obj.status() for key, value in self.extras.items(): bundle.data[key] = value return bundle
def create_course(self, form, affil): # Create the course. studentaffil = re.sub(r'\.fc\.', '.st.', affil.name) g = Group.objects.get_or_create(name=studentaffil)[0] fg = Group.objects.get_or_create(name=affil.name)[0] c = Course.objects.create( group=g, faculty_group=fg, title=form.cleaned_data.get('course_name')) # Add the current user as an instructor. c.group.user_set.add(self.request.user) c.faculty_group.user_set.add(self.request.user) c.add_detail('instructor', get_public_name(self.request.user, self.request)) # Get the year and term from the affil string. affil_dict = {} if hasattr(settings, 'COURSEAFFILS_COURSESTRING_MAPPER'): affil_dict = settings.COURSEAFFILS_COURSESTRING_MAPPER.to_dict( affil.name) if affil_dict: c.info.year = affil_dict.get('year') c.info.term = affil_dict.get('term') c.info.save() return c
def dehydrate(self, bundle): bundle.data['is_assignment'] = bundle.obj.is_assignment() bundle.data['is_selection_assignment'] = \ bundle.obj.is_selection_assignment() bundle.data['description'] = bundle.obj.description() bundle.data['is_response'] = bundle.obj.assignment() is not None bundle.data['attribution'] = bundle.obj.attribution() bundle.data['url'] = bundle.obj.get_absolute_url() bundle.data['due_date'] = bundle.obj.get_due_date() bundle.data['modified_date'] = bundle.obj.modified.strftime("%m/%d/%y") bundle.data['modified_time'] = bundle.obj.modified.strftime("%I:%M %p") bundle.data['editable'] = self.editable bundle.data['is_faculty'] = self.is_viewer_faculty bundle.data['submitted'] = bundle.obj.is_submitted() participants = bundle.obj.attribution_list() bundle.data['participants'] = [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, bundle.request), 'is_viewer': self.record_viewer == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)] bundle.data['status'] = bundle.obj.status() for key, value in self.extras.items(): bundle.data[key] = value return bundle
def dehydrate(self, bundle): bundle.data['is_assignment'] = \ bundle.obj.visibility_short() == 'Assignment' bundle.data['is_response'] = bundle.obj.assignment() is not None bundle.data['attribution'] = bundle.obj.attribution() bundle.data['url'] = bundle.obj.get_absolute_url() bundle.data['due_date'] = bundle.obj.get_due_date() bundle.data['modified_date'] = bundle.obj.modified.strftime("%m/%d/%y") bundle.data['modified_time'] = bundle.obj.modified.strftime("%I:%M %p") bundle.data['editable'] = self.editable bundle.data['is_faculty'] = self.is_viewer_faculty participants = bundle.obj.attribution_list() bundle.data['participants'] = [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, bundle.request), 'is_viewer': self.record_viewer == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)] bundle.data['status'] = bundle.obj.status() for key, value in self.extras.items(): bundle.data[key] = value return bundle
def browse_sources(request): c = request.course user = request.user archives = [] upload_archive = None for a in c.asset_set.archives().order_by('title'): archive = a.sources['archive'] thumb = a.sources.get('thumb',None) description = a.metadata().get('description','') uploader = a.metadata().get('upload', 0) archive_context = { "id":a.id, "title":a.title, "thumb":(None if not thumb else {"id":thumb.id, "url":thumb.url}), "archive":{"id":archive.id, "url":archive.url}, #is description a list or a string? "metadata": (description[0] if hasattr(description,'append') else description) } if (uploader[0] if hasattr(uploader,'append') else uploader): upload_archive = archive_context else: archives.append(archive_context) archives.sort(key=operator.itemgetter('title')) owners = [] if in_course(user.username, request.course) and (user.is_staff or user.has_perm('assetmgr.can_upload_for')): owners = [{ 'username': m.username, 'public_name': get_public_name(m, request) } for m in request.course.members] rv = {"archives":archives, "upload_archive": upload_archive, "is_faculty":c.is_faculty(user), "space_viewer":user, 'newsrc':request.GET.get('newsrc', ''), 'can_upload': course_details.can_upload(request.user, request.course), 'upload_service': getattr(settings,'UPLOAD_SERVICE',None), "help_browse_sources": UserSetting.get_setting(user, "help_browse_sources", True), "help_no_sources": UserSetting.get_setting(user, "help_no_sources", True), 'msg': request.GET.get('msg', ''), 'owners': owners, } if not rv['archives']: rv['faculty_assets'] = [a for a in Asset.objects.filter(c.faculty_filter).order_by('added') if a not in rv['archives'] ] if getattr(settings,'DJANGOSHERD_FLICKR_APIKEY',None): # MUST only contain string values for now!! # (see templates/assetmgr/bookmarklet.js to see why or fix) rv['bookmarklet_vars'] = {'flickr_apikey':settings.DJANGOSHERD_FLICKR_APIKEY } return rv
def homepage_project_json(request, projects, can_edit): project_json = [] for project in projects: the_json = {} the_json['id'] = project.id the_json['title'] = project.title the_json['url'] = project.get_absolute_url() the_json['due_date'] = project.get_due_date() participants = project.attribution_list() the_json['authors'] = [{ 'name': get_public_name(u, request), 'last': idx == (len(participants) - 1) } for idx, u in enumerate(participants)] the_json['modified_date'] = project.modified.strftime("%m/%d/%y") the_json['modified_time'] = project.modified.strftime("%I:%M %p") the_json['status'] = project.status() the_json['editable'] = can_edit if can_edit: feedback = project.feedback_discussion() if feedback: the_json['feedback'] = feedback.id parent_assignment = project.assignment() if parent_assignment: the_json['collaboration'] = {} the_json['collaboration']['title'] = parent_assignment.title the_json['collaboration']['url'] = \ parent_assignment.get_absolute_url() the_json['collaboration']['due_date'] = \ parent_assignment.get_due_date() is_assignment = project.is_assignment(request) if is_assignment: count = 0 for response in project.responses(request): if response.can_read(request): count += 1 the_json['responses'] = count the_json['display_as_assignment'] = \ is_assignment or parent_assignment is not None if is_assignment: the_json['is_assignment'] = True the_json['responses'] = len(project.responses(request)) project_json.append(the_json) return project_json
def homepage_project_json(request, projects, can_edit): project_json = [] for project in projects: the_json = {} the_json['id'] = project.id the_json['title'] = project.title the_json['url'] = project.get_absolute_url() the_json['due_date'] = project.get_due_date() participants = project.attribution_list() the_json['authors'] = [{ 'name': get_public_name(u, request), 'last': idx == (len(participants) - 1) } for idx, u in enumerate(participants)] the_json['modified_date'] = project.modified.strftime("%m/%d/%y") the_json['modified_time'] = project.modified.strftime("%I:%M %p") the_json['status'] = project.status() the_json['editable'] = can_edit if can_edit: feedback = project.feedback_discussion() if feedback: the_json['feedback'] = feedback.id parent_assignment = project.assignment() if parent_assignment: the_json['collaboration'] = {} the_json['collaboration']['title'] = parent_assignment.title the_json['collaboration']['url'] = \ parent_assignment.get_absolute_url() the_json['collaboration']['due_date'] = \ parent_assignment.get_due_date() is_assignment = project.is_assignment(request) if is_assignment: count = 0 for r in project.responses(request): if r.can_read(request): count += 1 the_json['responses'] = count the_json['display_as_assignment'] = \ is_assignment or parent_assignment is not None if is_assignment: the_json['is_assignment'] = True the_json['responses'] = len(project.responses(request)) project_json.append(the_json) return project_json
def dehydrate(self, bundle): bundle.data['is_essay_assignment'] = bundle.obj.is_essay_assignment() bundle.data['is_selection_assignment'] = \ bundle.obj.is_selection_assignment() bundle.data['is_sequence_assignment'] = \ bundle.obj.is_sequence_assignment() bundle.data['is_sequence'] = bundle.obj.is_sequence() bundle.data['description'] = bundle.obj.description() bundle.data['is_response'] = bundle.obj.assignment() is not None bundle.data['attribution'] = bundle.obj.attribution() if hasattr(self, 'request') and \ waffle.flag_is_active(self.request, 'addressable_courses') and \ hasattr(self.request, 'course'): bundle.data['url'] = reverse('project-workspace', kwargs={ 'course_pk': self.request.course.pk, 'project_id': bundle.obj.pk, }) else: bundle.data['url'] = bundle.obj.get_absolute_url() bundle.data['due_date'] = bundle.obj.get_due_date() bundle.data['modified_date'] = bundle.obj.modified.strftime("%m/%d/%y") bundle.data['modified_time'] = bundle.obj.modified.strftime("%I:%M %p") bundle.data['editable'] = self.editable bundle.data['is_faculty'] = self.is_viewer_faculty bundle.data['submitted'] = bundle.obj.is_submitted() participants = bundle.obj.attribution_list() bundle.data['participants'] = [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, bundle.request), 'is_viewer': self.record_viewer == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)] bundle.data['status'] = bundle.obj.status() for key, value in self.extras.items(): bundle.data[key] = value return bundle
def render_one(self, request, project, version_number=None): bundle = self.build_bundle(obj=project, request=request) dehydrated = self.full_dehydrate(bundle) project_ctx = self._meta.serializer.to_simple(dehydrated, None) project_ctx['body'] = project.body project_ctx['public_url'] = project.public_url() project_ctx['current_version'] = version_number project_ctx['visibility'] = project.visibility_short() project_type = ('assignment' if project.is_assignment(request.course, request.user) else 'composition') project_ctx['type'] = project_type assets, notes = self.related_assets_notes(request, project) data = { 'project': project_ctx, 'type': 'project', 'can_edit': self.editable, 'annotations': notes, 'assets': assets } data['responses'] = self.all_responses(request, project) data['response_count'] = len(data['responses']) my_responses = self.my_responses(request, project) if len(my_responses) == 1: data['my_response'] = my_responses[0] elif len(my_responses) > 1: data['my_responses'] = my_responses data['my_responses_count'] = len(my_responses) if project.is_participant(request.user): data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p")} for v in project.versions.order_by('-change_time')] if self.editable: projectform = ProjectForm(request, instance=project) data['form'] = { 'participants': projectform['participants'].__unicode__(), 'publish': projectform['publish'].__unicode__() } return data
def project_revisions(request, project_id): project = get_object_or_404(Project, pk=project_id, course=request.course) if not project.is_participant(request.user): return HttpResponseForbidden("forbidden") data = {} data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p")} for v in project.versions.order_by('-change_time')] return HttpResponse(simplejson.dumps(data, indent=2), mimetype='application/json')
def project_revisions(request, project_id): project = get_object_or_404(Project, pk=project_id, course=request.course) if not project.is_participant(request.user): return HttpResponseForbidden("forbidden") data = {} data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p")} for v in project.versions.order_by('-change_time')] return HttpResponse(json.dumps(data, indent=2), mimetype='application/json')
def init_created_course(self, course, affil): # Add the current user as an instructor. course.group.user_set.add(self.request.user) course.faculty_group.user_set.add(self.request.user) course.add_detail('instructor', get_public_name(self.request.user, self.request)) # Get the year and term from the affil string. affil_dict = {} if hasattr(settings, 'COURSEAFFILS_COURSESTRING_MAPPER'): affil_dict = settings.COURSEAFFILS_COURSESTRING_MAPPER.to_dict( affil.name) if affil_dict: course.info.year = affil_dict.get('year') course.info.term = affil_dict.get('term') course.info.save()
def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['project'] = self.project ctx['versions'] = [] fmt = "%m/%d/%y %I:%M %p" for v in self.project.versions(): author = User.objects.get(id=v.field_dict['author_id']) ctx['versions'].append({ 'modified': v.revision.date_created.strftime(fmt), 'author': get_public_name(author, self.request), 'version_number': v.revision_id }) return ctx
def __init__(self, request, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) lst = [(u.id, get_public_name(u, request)) for u in request.course.user_set.all()] self.fields['participants'].choices = sorted( lst, key=lambda participant: participant[1]) self.fields['participants'].widget.attrs = { 'id': "id_participants_%s" % self.instance.id } col = kwargs['instance'].collaboration() if col: pol = col._policy.policy_name if pol not in dict(self.fields['publish'].choices): self.fields['publish'].choices.append((pol, pol)) self.initial['publish'] = pol if request.course.is_faculty(request.user): # Faculty self.fields['publish'].choices = \ [choice for choice in self.fields['publish'].choices if choice[0] in PUBLISH_OPTIONS_FACULTY] else: # Student if kwargs['instance'].assignment(): # Assignment response self.fields['publish'].choices = \ [choice for choice in self.fields['publish'].choices if choice[0] in PUBLISH_OPTIONS_STUDENT_ASSIGNMENT] else: self.fields['publish'].choices = \ [choice for choice in self.fields['publish'].choices if choice[0] in PUBLISH_OPTIONS_STUDENT_COMPOSITION] if course_details.allow_public_compositions(request.course): self.fields['publish'].choices.append(PUBLISH_OPTIONS_PUBLIC) self.fields['participants'].required = False self.fields['body'].required = False self.fields['submit'].required = False self.fields['publish'].required = False # for structured collaboration self.fields['title'].widget.attrs['maxlength'] = 80
def project_revisions(request, project_id): project = get_object_or_404(Project, pk=project_id, course=request.course) if not project.is_participant(request.user): return HttpResponseForbidden("forbidden") data = {} data["revisions"] = [ { "version_number": v.version_number, "versioned_id": v.versioned_id, "author": get_public_name(v.instance().author, request), "modified": v.modified.strftime("%m/%d/%y %I:%M %p"), } for v in project.versions.order_by("-change_time") ] return HttpResponse(simplejson.dumps(data, indent=2), mimetype="application/json")
def my_responses(self, request, project): my_responses = [] for response in project.responses_by(request.course, request.user, request.user): obj = {'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': []} last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last}) my_responses.append(obj) return my_responses
def project_revisions(request, project_id): project = get_object_or_404(Project, pk=project_id, course=request.course) if not project.is_participant(request.user): return HttpResponseForbidden("forbidden") data = {'revisions': []} fmt = "%m/%d/%y %I:%M %p" for v in project.versions(): author = User.objects.get(id=v.field_dict['author']) data['revisions'].append({ 'version_number': v.revision_id, 'versioned_id': v.object_id, 'author': get_public_name(author, request), 'modified': v.revision.date_created.strftime(fmt) }) return HttpResponse(json.dumps(data, indent=2), content_type='application/json')
def project_revisions(request, project_id): project = get_object_or_404(Project, pk=project_id, course=request.course) if not project.is_participant(request.user): return HttpResponseForbidden("forbidden") data = {'revisions': []} fmt = "%m/%d/%y %I:%M %p" for v in project.versions(): author = User.objects.get(id=v.field_dict['author_id']) data['revisions'].append({ 'version_number': v.revision_id, 'versioned_id': v.object_id, 'author': get_public_name(author, request), 'modified': v.revision.date_created.strftime(fmt) }) return HttpResponse(json.dumps(data, indent=2), content_type='application/json')
def __init__(self, request, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) lst = [(u.id, get_public_name(u, request)) for u in request.course.user_set.all()] self.fields['participants'].choices = sorted( lst, key=lambda participant: participant[1]) self.fields['participants'].widget.attrs = { 'id': "id_participants_%s" % self.instance.id } project = kwargs['instance'] if project: # set initial publish value col = project.get_collaboration() if col: self.initial['publish'] = col.policy_record.policy_name else: self.instance = None choices = self.get_choices(request, project) self.fields['publish'].choices = choices # response view policy. limit choices if there is no project # or the project is a selection assignment if (not project or not ( project.is_composition() or project.is_sequence())): choices = [RESPONSE_VIEW_NEVER] if all_selections_are_visible(request.course): choices.append(RESPONSE_VIEW_SUBMITTED) choices.append(RESPONSE_VIEW_ALWAYS) self.fields['response_view_policy'].choices = choices self.fields['participants'].required = False self.fields['body'].required = False self.fields['submit'].required = False self.fields['publish'].required = False # for structured collaboration self.fields['title'].widget.attrs['maxlength'] = 80
def __init__(self,request, *args, **kwargs): super(ProjectForm,self).__init__(*args,**kwargs) self.fields['participants'].widget = widgets.FilteredSelectMultiple("participants",False) lst = [(u.id,get_public_name(u, request)) for u in request.course.user_set.all()] self.fields['participants'].choices = sorted(lst, key=lambda participant: participant[1]) # sort by name col = kwargs['instance'].collaboration() if col: pol = col._policy.policy_name if pol not in dict(self.fields['publish'].choices): self.fields['publish'].choices.append( (pol,pol) ) self.initial['publish'] = pol if not request.course.is_faculty(request.user): self.fields['publish'].choices = [choice for choice in self.fields['publish'].choices if choice[0] not in PUBLISH_OPTIONS_FACULTY_ONLY] if not course_details.allow_public_compositions(request.course): self.fields['publish'].choices = [choice for choice in self.fields['publish'].choices if choice[0] not in PUBLISH_OPTIONS_PUBLIC] #not restrictive enough -- people can add children to their own projects # is that a good idea? # necessary to add a discussion to it, but maybe that's a workaround # how about we just have people 'create' a project from the assignment page for now. #self.fields['parent'].choices = [(sc.id,sc.title) for sc in # Collaboration.objects.filter(context=request.collaboration_context, # content_type = ContentType.objects.get_for_model(Project)) # if sc.permission_to('add_child',request) # ] self.fields['participants'].required = False self.fields['body'].required = False self.fields['submit'].required = False self.fields['publish'].required = False self.fields['title'].widget.attrs['maxlength'] = 80 #for structured collaboration
def __init__(self, request, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) lst = [(u.id, get_public_name(u, request)) for u in request.course.user_set.all()] self.fields['participants'].choices = sorted( lst, key=lambda participant: participant[1]) self.fields['participants'].widget.attrs = { 'id': "id_participants_%s" % self.instance.id } project = kwargs['instance'] if project: # set initial publish value col = project.get_collaboration() if col: self.initial['publish'] = col.policy_record.policy_name else: self.instance = None choices = self.get_choices(request, project) self.fields['publish'].choices = choices # response view policy. limit choices if there is no project # or the project is a selection assignment if (not project or not (project.is_composition() or project.is_sequence())): choices = [RESPONSE_VIEW_NEVER] if all_selections_are_visible(request.course): choices.append(RESPONSE_VIEW_SUBMITTED) choices.append(RESPONSE_VIEW_ALWAYS) self.fields['response_view_policy'].choices = choices self.fields['participants'].required = False self.fields['body'].required = False self.fields['submit'].required = False self.fields['publish'].required = False # for structured collaboration self.fields['title'].widget.attrs['maxlength'] = 80
def my_responses(self, request, project): ctx = [] responses = project.responses(request.course, request.user, request.user) for response in responses: obj = { 'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': [] } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last }) ctx.append(obj) return ctx
def __init__(self,request, *args, **kwargs): super(ProjectForm,self).__init__(*args,**kwargs) self.fields['participants'].widget = widgets.FilteredSelectMultiple("participants",False) lst = [(u.id,get_public_name(u, request)) for u in request.course.user_set.all()] self.fields['participants'].choices = sorted(lst, key=lambda participant: participant[1]) # sort by name col = kwargs['instance'].collaboration() if col: pol = col._policy.policy_name if pol not in dict(self.fields['publish'].choices): self.fields['publish'].choices.append( (pol,pol) ) self.initial['publish'] = pol if not request.course.is_faculty(request.user): self.fields['publish'].choices = [choice for choice in self.fields['publish'].choices if choice[0] not in PUBLISH_OPTIONS_FACULTY_ONLY] #not restrictive enough -- people can add children to their own projects # is that a good idea? # necessary to add a discussion to it, but maybe that's a workaround # how about we just have people 'create' a project from the assignment page for now. #self.fields['parent'].choices = [(sc.id,sc.title) for sc in # Collaboration.objects.filter(context=request.collaboration_context, # content_type = ContentType.objects.get_for_model(Project)) # if sc.permission_to('add_child',request) # ] self.fields['participants'].required = False self.fields['body'].required = False self.fields['submit'].required = False self.fields['publish'].required = False self.fields['title'].widget.attrs['maxlength'] = 80 #for structured collaboration
def get_records(request, record_owner, projects, assignments, assets): course = request.course logged_in_user = request.user # Can the record_owner edit the records viewing_my_records = (record_owner == logged_in_user) viewing_faculty_records = record_owner and course.is_faculty(record_owner) # Allow the logged in user to add assets to his composition citable = request.GET.has_key('citable') and request.GET.get('citable') == 'true' # Is the current user faculty OR staff is_faculty = course.is_faculty(logged_in_user) # Does the course allow viewing other user selections? owner_selections_are_visible = course_details.all_selections_are_visible(course) or \ viewing_my_records or viewing_faculty_records or is_faculty # Filter the assets for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [asset for asset in assets if filter_by[fil](asset, filter_value, record_owner)] active_filters = get_active_filters(request, filter_by) # Spew out json for the assets asset_json = [] options = { 'owner_selections_are_visible': request.GET.has_key('annotations') and owner_selections_are_visible, 'all_selections_are_visible': course_details.all_selections_are_visible(course) or is_faculty, 'can_edit': viewing_my_records, 'citable': citable } for asset in assets: asset_json.append(homepage_asset_json(request, asset, logged_in_user, record_owner, options)) # Spew out json for the projects project_json = [] for p in projects: project_json.append(homepage_project_json(request, p, viewing_my_records)) # Tags tags = [] if record_owner: if owner_selections_are_visible: # Tags for selected user tags = Tag.objects.usage_for_queryset( record_owner.sherdnote_set.filter(asset__course=course), counts=True) else: if owner_selections_are_visible: # Tags for the whole class tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter(asset__course=course), counts=True) else: # Tags for myself and faculty members tags = Tag.objects.usage_for_queryset( logged_in_user.sherdnote_set.filter(asset__course=course), counts=True) for f in course.faculty: tags.extend(Tag.objects.usage_for_queryset( f.sherdnote_set.filter(asset__course=course), counts=True)) tags.sort(lambda a, b:cmp(a.name.lower(), b.name.lower())) # Assemble the context data = { 'assets': asset_json, 'assignments' : [ {'id': a.id, 'url': a.get_absolute_url(), 'title': a.title, 'modified': a.modified.strftime("%m/%d/%y %I:%M %p")} for a in assignments], 'projects' : project_json, 'tags': [ { 'name': tag.name } for tag in tags ], 'active_filters': active_filters, 'space_viewer' : { 'username': logged_in_user.username, 'public_name': get_public_name(logged_in_user, request), 'can_manage': (logged_in_user.is_staff and not record_owner) }, 'editable' : viewing_my_records, 'citable' : citable, 'owners' : [{ 'username': m.username, 'public_name': get_public_name(m, request) } for m in request.course.members], 'compositions' : len(projects) > 0 or len(assignments) > 0, 'is_faculty': is_faculty, } if record_owner: data['space_owner'] = { 'username': record_owner.username, 'public_name': get_public_name(record_owner, request) } json_stream = simplejson.dumps(data, indent=2) return HttpResponse(json_stream, mimetype='application/json')
def render_one(self, request, project, version_number=None): bundle = self.build_bundle(obj=project, request=request) dehydrated = self.full_dehydrate(bundle) project_ctx = self._meta.serializer.to_simple(dehydrated, None) project_ctx['body'] = project.body project_ctx['public_url'] = project.public_url() project_ctx['current_version'] = version_number project_ctx['visibility'] = project.visibility_short() project_ctx['type'] = ('assignment' if project.is_assignment(request) else 'composition') rand = ''.join([choice(letters) for i in range(5)]) asset_resource = AssetResource() sherd_resource = SherdNoteResource() assets = {} notes = [] for note in project.citations(): notes.append(sherd_resource.render_one(request, note, rand)) if (note.title not in ["Annotation Deleted", 'Asset Deleted']): key = '%s_%s' % (rand, note.asset.pk) if key not in assets.keys(): assets[key] = \ asset_resource.render_one(request, note.asset) data = { 'project': project_ctx, 'type': 'project', 'can_edit': self.editable, 'annotations': notes, 'assets': assets } data['responses'] = [] for response in project.responses(request): if response.can_read(request): obj = { 'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': [] } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last }) data['responses'].append(obj) data['response_count'] = len(data['responses']) my_responses = [] for response in project.responses_by(request, request.user): obj = { 'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime(self.date_fmt), 'attribution_list': [] } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last }) my_responses.append(obj) if len(my_responses) == 1: data['my_response'] = my_responses[0] elif len(my_responses) > 1: data['my_responses'] = my_responses data['my_responses_count'] = len(my_responses) if project.is_participant(request.user): data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p") } for v in project.versions.order_by('-change_time')] if self.editable: projectform = ProjectForm(request, instance=project) data['form'] = { 'participants': projectform['participants'].__unicode__(), 'publish': projectform['publish'].__unicode__() } return data
def render(self, context): user_s = self.vars['user'].resolve(context) if self.truncate is not None: user_s = user_s[:self.truncate] return get_public_name(user_s, context['request'])
def dehydrate(self, bundle): bundle.data["public_name"] = get_public_name(bundle.obj, bundle.request) return bundle
def composition_project_json(request, project, can_edit, version_number=None): ''' JSON representation for a project. Includes: * basic project information * assets * annotations * responses (if applicable & permissable) * revisions (if permissable) * a project participant form (if permissable) ''' rand = ''.join([choice(letters) for i in range(5)]) versions = project.versions.order_by('-change_time') participants = project.attribution_list() is_assignment = project.is_assignment(request) data = { 'project': { 'id': project.pk, 'title': project.title, 'url': project.get_absolute_url(), 'body': project.body, 'participants': [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, request), 'is_viewer': request.user.username == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)], 'public_url': project.public_url(), 'visibility': project.visibility_short(), 'username': request.user.username, 'type': 'assignment' if is_assignment else 'composition', 'current_version': version_number if version_number else None, 'create_selection': is_assignment, 'is_assignment': is_assignment }, 'assets': dict([('%s_%s' % (rand, ann.asset.pk), ann.asset.sherd_json(request)) for ann in project.citations() if ann.title != "Annotation Deleted" and ann.title != 'Asset Deleted']), 'annotations': [ ann.sherd_json(request, rand, ('title', 'author')) for ann in project.citations() ], 'type': 'project', 'can_edit': can_edit, } data['responses'] = [] for r in project.responses(request): if r.can_read(request): obj = { 'url': r.get_absolute_url(), 'title': r.title, 'modified': r.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': [] } x = len(r.attribution_list()) - 1 for idx, author in enumerate(r.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == x }) data['responses'].append(obj) data['response_count'] = len(data['responses']) my_responses = [] for r in project.responses_by(request, request.user): obj = { 'url': r.get_absolute_url(), 'title': r.title, 'modified': r.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': [] } x = len(r.attribution_list()) - 1 for idx, author in enumerate(r.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == x }) my_responses.append(obj) if len(my_responses) == 1: data['my_response'] = my_responses[0] elif len(my_responses) > 1: data['my_responses'] = my_responses data['my_responses_count'] = len(my_responses) if project.is_participant(request.user): data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p") } for v in versions] if can_edit: projectform = ProjectForm(request, instance=project) data['form'] = { 'participants': projectform['participants'].__unicode__(), 'publish': projectform['publish'].__unicode__() } return data
def render_one(self, request, project, version_number=None): bundle = self.build_bundle(obj=project, request=request) dehydrated = self.full_dehydrate(bundle) project_ctx = self._meta.serializer.to_simple(dehydrated, None) project_ctx["body"] = project.body project_ctx["public_url"] = project.public_url() project_ctx["current_version"] = version_number project_ctx["visibility"] = project.visibility_short() project_ctx["type"] = "assignment" if project.is_assignment(request) else "composition" rand = "".join([choice(letters) for i in range(5)]) asset_resource = AssetResource() sherd_resource = SherdNoteResource() assets = {} notes = [] for note in project.citations(): notes.append(sherd_resource.render_one(request, note, rand)) if note.title not in ["Annotation Deleted", "Asset Deleted"]: key = "%s_%s" % (rand, note.asset.pk) if key not in assets.keys(): assets[key] = asset_resource.render_one(request, note.asset) data = { "project": project_ctx, "type": "project", "can_edit": self.editable, "annotations": notes, "assets": assets, } data["responses"] = [] for response in project.responses(request): if response.can_read(request): obj = { "url": response.get_absolute_url(), "title": response.title, "modified": response.modified.strftime(self.date_fmt), "attribution_list": [], } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj["attribution_list"].append({"name": get_public_name(author, request), "last": idx == last}) data["responses"].append(obj) data["response_count"] = len(data["responses"]) my_responses = [] for response in project.responses_by(request, request.user): obj = { "url": response.get_absolute_url(), "title": response.title, "modified": response.modified.strftime(self.date_fmt), "attribution_list": [], } last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj["attribution_list"].append({"name": get_public_name(author, request), "last": idx == last}) my_responses.append(obj) if len(my_responses) == 1: data["my_response"] = my_responses[0] elif len(my_responses) > 1: data["my_responses"] = my_responses data["my_responses_count"] = len(my_responses) if project.is_participant(request.user): data["revisions"] = [ { "version_number": v.version_number, "versioned_id": v.versioned_id, "author": get_public_name(v.instance().author, request), "modified": v.modified.strftime("%m/%d/%y %I:%M %p"), } for v in project.versions.order_by("-change_time") ] if self.editable: projectform = ProjectForm(request, instance=project) data["form"] = { "participants": projectform["participants"].__unicode__(), "publish": projectform["publish"].__unicode__(), } return data
def author_name(request, annotation, key): if not annotation.author_id: return None return 'author_name', get_public_name(annotation.author, request)
def get_records(user, course, request): c = course today = datetime.date.today() editable = (user == request.user) #bad language, we should change this to user_of_assets or something space_viewer = request.user if request.GET.has_key('as') and request.user.is_staff: space_viewer = get_object_or_404(User, username=request.GET['as']) assignments = [] responder = None if user == 'all': archives = list(course.asset_set.archives()) assets = [ a for a in Asset.objects.filter(course=c).extra( select={ 'lower_title': 'lower(assetmgr_asset.title)' }).select_related().order_by('lower_title') if a not in archives ] user = None all_tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter(asset__course=course), counts=True) all_tags.sort(lambda a, b: cmp(a.name.lower(), b.name.lower())) tags = calculate_cloud(all_tags) projects = [ p for p in Project.objects.filter(course=c, submitted=True).order_by('title') if p.visible(request) ] else: assets = annotated_by(Asset.objects.filter(course=c), user, include_archives=c.is_faculty(user)) tags = calculate_cloud( Tag.objects.usage_for_queryset( user.sherdnote_set.filter(asset__course=c), counts=True)) projects = Project.get_user_projects(user, c).order_by('-modified') if not editable: projects = [p for p in projects if p.visible(request)] project_type = ContentType.objects.get_for_model(Project) assignments = [] maybe_assignments = Project.objects.filter(c.faculty_filter) for assignment in maybe_assignments: if not assignment.visible(request): continue if assignment in projects: continue if is_unanswered_assignment(assignment, user, request, project_type): assignments.append(assignment) if user.id == space_viewer.id: responder = space_viewer.username for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [ asset for asset in assets if filter_by[fil](asset, filter_value, user) ] active_filters = get_active_filters(request, filter_by) if request.is_ajax(): asset_json = [] for asset in assets: the_json = asset.sherd_json(request) gannotation, created = SherdNote.objects.global_annotation( asset, user or space_viewer, auto_create=False) if gannotation: the_json['global_annotation'] = gannotation.sherd_json( request, 'x', ('tags', 'body')) the_json['editable'] = editable annotations = [] if request.GET.has_key('annotations'): # @todo: refactor this serialization into a common place. def author_name(request, annotation, key): if not annotation.author_id: return None return 'author_name', get_public_name( annotation.author, request) for ann in asset.sherdnote_set.filter(range1__isnull=False, author=user): annotations.append( ann.sherd_json(request, 'x', ('title', 'author', 'tags', author_name, 'body', 'modified', 'timecode'))) the_json['annotations'] = annotations asset_json.append(the_json) project_json = [] for p in projects: the_json = {} the_json['id'] = p.id the_json['title'] = p.title the_json['url'] = p.get_absolute_url() participants = p.attribution_list() the_json['authors'] = [{ 'name': get_public_name(u, request) } for u in participants] the_json['modified'] = p.modified.strftime("%m/%d/%y %I:%M %p") the_json['status'] = p.status() the_json['editable'] = editable feedback = p.feedback_discussion() if feedback: the_json['feedback'] = feedback.id collaboration = p.collaboration() if collaboration: collaboration_parent = collaboration.get_parent() if collaboration_parent: the_json['collaboration'] = {} the_json['collaboration'][ 'title'] = collaboration_parent.title if collaboration_parent.content_object: the_json['collaboration'][ 'url'] = collaboration_parent.content_object.get_absolute_url( ) project_json.append(the_json) data = { 'assets': asset_json, 'assignments': [{ 'id': a.id, 'responder': responder, 'url': a.get_absolute_url(), 'title': a.title, 'modified': a.modified.strftime("%m/%d/%y %I:%M %p") } for a in assignments], 'projects': project_json, 'tags': [{ 'name': tag.name } for tag in tags], 'active_filters': active_filters, 'space_viewer': { 'username': space_viewer.username, 'public_name': get_public_name(space_viewer, request), 'can_manage': (space_viewer.is_staff and not user) }, 'editable': editable, 'owners': [{ 'username': m.username, 'public_name': get_public_name(m, request) } for m in request.course.members], 'compositions': len(projects) > 0 or len(assignments) > 0, 'is_faculty': c.is_faculty(space_viewer), } if user: data['space_owner'] = { 'username': user.username, 'public_name': get_public_name(user, request) } json_stream = simplejson.dumps(data, indent=2) return HttpResponse(json_stream, mimetype='application/json') else: dates = ( ('today', 'today'), ('yesterday', 'yesterday'), ('lastweek', 'within the last week'), ) return { 'assets': assets, 'assignments': assignments, 'projects': projects, 'tags': tags, 'dates': dates, 'space_owner': user, 'space_viewer': space_viewer, 'editable': editable, 'active_filters': active_filters, }
def test_get_public_name(self): r = DummyRequest() assert get_public_name(self.student, r) == "student" assert get_public_name([self.student, ], r) == "student"
def project_json(request, project, can_edit, version_number=None): ''' JSON representation for a project. Includes: * basic project information * assets * annotations * responses (if applicable & permissable) * revisions (if permissable) * a project participant form (if permissable) ''' rand = ''.join([choice(letters) for i in range(5)]) versions = project.versions.order_by('-change_time') participants = project.attribution_list() is_assignment = project.is_assignment(request) data = { 'project': { 'title': project.title, 'body': project.body, 'participants': [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, request), 'is_viewer': request.user.username == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)], 'id': project.pk, 'url': project.get_absolute_url(), 'public_url': project.public_url(), 'visibility': project.visibility_short(), 'username': request.user.username, 'type': 'assignment' if is_assignment else 'composition', 'current_version': version_number if version_number else None, 'create_selection': is_assignment, 'is_assignment': is_assignment }, 'assets': dict([('%s_%s' % (rand,ann.asset.pk), ann.asset.sherd_json(request) ) for ann in project.citations() if ann.title and ann.title != "Annotation Deleted" and ann.title != 'Asset Deleted' ]), 'annotations': [ ann.sherd_json(request, rand, ('title','author')) for ann in project.citations() ], 'type': 'project', 'can_edit': can_edit, } data['responses'] = [] for r in project.responses(request): if r.can_read(request): obj = { 'url': r.get_absolute_url(), 'title': r.title, 'modified': r.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': [] } x = len(r.attribution_list()) - 1 for idx, author in enumerate(r.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == x }) data['responses'].append(obj) data['response_count'] = len(data['responses']) my_responses = [] for r in project.responses_by(request, request.user): obj = { 'url': r.get_absolute_url(), 'title': r.title, 'modified': r.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': [] } x = len(r.attribution_list()) - 1 for idx, author in enumerate(r.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == x }) my_responses.append(obj) if len(my_responses) == 1: data['my_response'] = my_responses[0] elif len(my_responses) > 1: data['my_responses'] = my_responses data['my_responses_count'] = len(my_responses) if project.is_participant(request.user): data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p") } for v in versions ] if can_edit: projectform = ProjectForm(request, instance=project) data['form'] = { 'participants': projectform['participants'].__unicode__(), 'publish': projectform['publish'].__unicode__() } return data
def get_records(user, course, request): c = course today = datetime.date.today() editable = (user==request.user) #bad language, we should change this to user_of_assets or something space_viewer = request.user if request.GET.has_key('as') and request.user.is_staff: space_viewer = get_object_or_404(User, username=request.GET['as']) assignments = [] responder = None if user == 'all': archives = list(course.asset_set.archives()) assets = [a for a in Asset.objects.filter(course=c).extra( select={'lower_title': 'lower(assetmgr_asset.title)'} ).select_related().order_by('lower_title') if a not in archives] user = None all_tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter( asset__course=course), counts=True) all_tags.sort(lambda a,b:cmp(a.name.lower(),b.name.lower())) tags = calculate_cloud(all_tags) projects = [p for p in Project.objects.filter(course=c, submitted=True).order_by('title') if p.visible(request)] else: assets = annotated_by(Asset.objects.filter(course=c), user, include_archives=c.is_faculty(user) ) tags = calculate_cloud(Tag.objects.usage_for_queryset( user.sherdnote_set.filter( asset__course=c), counts=True)) projects = Project.get_user_projects(user, c).order_by('-modified') if not editable: projects = [p for p in projects if p.visible(request)] project_type = ContentType.objects.get_for_model(Project) assignments = [] maybe_assignments = Project.objects.filter( c.faculty_filter) for assignment in maybe_assignments: if not assignment.visible(request): continue if assignment in projects: continue if is_unanswered_assignment(assignment, user, request, project_type): assignments.append(assignment) if user.id == space_viewer.id: responder = space_viewer.username for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [asset for asset in assets if filter_by[fil](asset, filter_value, user)] active_filters = get_active_filters(request, filter_by) if request.is_ajax(): asset_json = [] for asset in assets: the_json = asset.sherd_json(request) gannotation, created = SherdNote.objects.global_annotation(asset, user or space_viewer, auto_create=False) if gannotation: the_json['global_annotation'] = gannotation.sherd_json(request, 'x', ('tags','body') ) the_json['editable'] = editable annotations = [] if request.GET.has_key('annotations'): # @todo: refactor this serialization into a common place. def author_name(request, annotation, key): if not annotation.author_id: return None return 'author_name',get_public_name(annotation.author, request) for ann in asset.sherdnote_set.filter(range1__isnull=False,author=user): annotations.append( ann.sherd_json(request, 'x', ('title','author','tags',author_name,'body','modified', 'timecode') ) ) the_json['annotations'] = annotations asset_json.append(the_json) project_json = [] for p in projects: the_json = {} the_json['id'] = p.id the_json['title'] = p.title the_json['url'] = p.get_absolute_url() participants = p.attribution_list() the_json['authors'] = [ {'name': get_public_name(u, request) } for u in participants] the_json['modified'] = p.modified.strftime("%m/%d/%y %I:%M %p") the_json['status'] = p.status() the_json['editable'] = editable feedback = p.feedback_discussion() if feedback: the_json['feedback'] = feedback.id collaboration = p.collaboration() if collaboration: collaboration_parent = collaboration.get_parent() if collaboration_parent: the_json['collaboration'] = {} the_json['collaboration']['title'] = collaboration_parent.title if collaboration_parent.content_object: the_json['collaboration']['url'] = collaboration_parent.content_object.get_absolute_url() project_json.append(the_json) data = {'assets': asset_json, 'assignments' : [ {'id': a.id, 'responder': responder, 'url': a.get_absolute_url(), 'title': a.title, 'modified': a.modified.strftime("%m/%d/%y %I:%M %p")} for a in assignments], 'projects' : project_json, 'tags': [ { 'name': tag.name } for tag in tags ], 'active_filters': active_filters, 'space_viewer' : { 'username': space_viewer.username, 'public_name': get_public_name(space_viewer, request), 'can_manage': (space_viewer.is_staff and not user) }, 'editable' : editable, 'owners' : [{ 'username': m.username, 'public_name': get_public_name(m, request) } for m in request.course.members], 'compositions' : len(projects) > 0 or len(assignments) > 0, 'is_faculty': c.is_faculty(space_viewer), } if user: data['space_owner'] = { 'username': user.username, 'public_name': get_public_name(user, request) } json_stream = simplejson.dumps(data, indent=2) return HttpResponse(json_stream, mimetype='application/json') else: dates = (('today','today'), ('yesterday','yesterday'), ('lastweek','within the last week'),) return { 'assets' : assets, 'assignments' : assignments, 'projects' : projects, 'tags' : tags, 'dates' : dates, 'space_owner' : user, 'space_viewer' : space_viewer, 'editable' : editable, 'active_filters': active_filters, }
def composition_project_json(request, project, can_edit, version_number=None): ''' JSON representation for a project. Includes: * basic project information * assets * annotations * responses (if applicable & permissable) * revisions (if permissable) * a project participant form (if permissable) ''' rand = ''.join([choice(letters) for i in range(5)]) participants = project.attribution_list() is_assignment = project.is_assignment(request) course = request.course if request.course \ else request.collaboration_context.content_object asset_resource = AssetSummaryResource() sherd_resource = SherdNoteResource() citations = project.citations() data = { 'project': { 'id': project.pk, 'title': project.title, 'url': project.get_absolute_url(), 'due_date': project.get_due_date(), 'body': project.body, 'participants': [{ 'name': p.get_full_name(), 'username': p.username, 'public_name': get_public_name(p, request), 'is_viewer': request.user.username == p.username, 'last': idx == (len(participants) - 1) } for idx, p in enumerate(participants)], 'public_url': project.public_url(), 'visibility': project.visibility_short(), 'username': request.user.username, 'type': 'assignment' if is_assignment else 'composition', 'description': project.description(), 'current_version': version_number if version_number else None, 'create_selection': is_assignment, 'is_assignment': is_assignment, 'course_title': course.title }, 'type': 'project', 'can_edit': can_edit, 'annotations': [sherd_resource.render_one(request, ann, rand) for ann in citations], } assets = {} for ann in citations: if ann.title != "Annotation Deleted" and ann.title != 'Asset Deleted': key = '%s_%s' % (rand, ann.asset.pk) if key not in assets: assets[key] = asset_resource.render_one(request, ann.asset) data['assets'] = assets data['responses'] = [] for response in project.responses(request): if response.can_read(request): obj = {'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': []} last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({ 'name': get_public_name(author, request), 'last': idx == last}) data['responses'].append(obj) data['response_count'] = len(data['responses']) my_responses = [] for response in project.responses_by(request, request.user): obj = {'url': response.get_absolute_url(), 'title': response.title, 'modified': response.modified.strftime("%m/%d/%y %I:%M %p"), 'attribution_list': []} last = len(response.attribution_list()) - 1 for idx, author in enumerate(response.attribution_list()): obj['attribution_list'].append({'name': get_public_name(author, request), 'last': idx == last}) my_responses.append(obj) if len(my_responses) == 1: data['my_response'] = my_responses[0] elif len(my_responses) > 1: data['my_responses'] = my_responses data['my_responses_count'] = len(my_responses) if project.is_participant(request.user): data['revisions'] = [{ 'version_number': v.version_number, 'versioned_id': v.versioned_id, 'author': get_public_name(v.instance().author, request), 'modified': v.modified.strftime("%m/%d/%y %I:%M %p")} for v in project.versions.order_by('-change_time')] if can_edit: projectform = ProjectForm(request, instance=project) data['form'] = { 'participants': projectform['participants'].__unicode__(), 'publish': projectform['publish'].__unicode__() } return data
def author_name(request, annotation, key): if not annotation.author_id: return None return 'author_name',get_public_name(annotation.author, request)
def dehydrate(self, bundle): bundle.data['public_name'] = get_public_name(bundle.obj, bundle.request) return bundle
def test_get_public_name(self): r = DummyRequest() self.assertEqual(get_public_name(self.student, r), "student") self.assertEqual(get_public_name([self.student, ], r), "student")
def get_records(request, record_owner, projects, assignments, assets): course = request.course logged_in_user = request.user # Can the record_owner edit the records viewing_my_records = (record_owner == logged_in_user) viewing_faculty_records = record_owner and course.is_faculty(record_owner) # Allow the logged in user to add assets to his composition citable = request.GET.has_key('citable') and request.GET.get( 'citable') == 'true' # Is the current user faculty OR staff is_faculty = course.is_faculty(logged_in_user) # Does the course allow viewing other user selections? owner_selections_are_visible = course_details.all_selections_are_visible(course) or \ viewing_my_records or viewing_faculty_records or is_faculty # Filter the assets for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [ asset for asset in assets if filter_by[fil](asset, filter_value, record_owner) ] active_filters = get_active_filters(request, filter_by) # Spew out json for the assets asset_json = [] options = { 'owner_selections_are_visible': request.GET.has_key('annotations') and owner_selections_are_visible, 'all_selections_are_visible': course_details.all_selections_are_visible(course) or is_faculty, 'can_edit': viewing_my_records, 'citable': citable } for asset in assets: asset_json.append( homepage_asset_json(request, asset, logged_in_user, record_owner, options)) # Spew out json for the projects project_json = [] for p in projects: project_json.append( homepage_project_json(request, p, viewing_my_records)) # Tags tags = [] if record_owner: if owner_selections_are_visible: # Tags for selected user tags = Tag.objects.usage_for_queryset( record_owner.sherdnote_set.filter(asset__course=course), counts=True) else: if owner_selections_are_visible: # Tags for the whole class tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter(asset__course=course), counts=True) else: # Tags for myself and faculty members tags = Tag.objects.usage_for_queryset( logged_in_user.sherdnote_set.filter(asset__course=course), counts=True) for f in course.faculty: tags.extend( Tag.objects.usage_for_queryset( f.sherdnote_set.filter(asset__course=course), counts=True)) tags.sort(lambda a, b: cmp(a.name.lower(), b.name.lower())) # Assemble the context data = { 'assets': asset_json, 'assignments': [{ 'id': a.id, 'url': a.get_absolute_url(), 'title': a.title, 'modified': a.modified.strftime("%m/%d/%y %I:%M %p") } for a in assignments], 'projects': project_json, 'tags': [{ 'name': tag.name } for tag in tags], 'active_filters': active_filters, 'space_viewer': { 'username': logged_in_user.username, 'public_name': get_public_name(logged_in_user, request), 'can_manage': (logged_in_user.is_staff and not record_owner) }, 'editable': viewing_my_records, 'citable': citable, 'owners': [{ 'username': m.username, 'public_name': get_public_name(m, request) } for m in request.course.members], 'compositions': len(projects) > 0 or len(assignments) > 0, 'is_faculty': is_faculty, } if record_owner: data['space_owner'] = { 'username': record_owner.username, 'public_name': get_public_name(record_owner, request) } json_stream = simplejson.dumps(data, indent=2) return HttpResponse(json_stream, mimetype='application/json')