def file_edit(request,group_id,_id): ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False : group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass file_node = collection.File.one({"_id": ObjectId(_id)}) if request.method == "POST": get_node_common_fields(request, file_node, group_id, GST_FILE) file_node.save() return HttpResponseRedirect(reverse('file_detail', kwargs={'group_id': group_id, '_id': file_node._id})) else: return render_to_response("ndf/document_edit.html", { 'node': file_node, 'group_id': group_id, 'groupid':group_id }, context_instance=RequestContext(request) )
def add_sub_themes(request, group_id): if request.is_ajax() and request.method == "POST": context_node_id = request.POST.get("context_node", '') sub_theme_name = request.POST.get("sub_theme_name", '') themes_list = request.POST.get("nodes_list", '') themes_list = themes_list.replace(""","'") themes_list = ast.literal_eval(themes_list) theme_GST = collection.Node.one({'_type': 'GSystemType', 'name': 'Theme'}) topic_GST = collection.Node.one({'_type': 'GSystemType', 'name': 'Topic'}) context_node = collection.Node.one({'_id': ObjectId(context_node_id) }) # Save the sub-theme first if sub_theme_name: if not sub_theme_name.upper() in (theme_name.upper() for theme_name in themes_list): node = collection.GSystem() get_node_common_fields(request, node, group_id, theme_GST) node.save() node.reload() # Add this sub-theme into context nodes collection_set collection.update({'_id': context_node._id}, {'$push': {'collection_set': ObjectId(node._id) }}, upsert=False, multi=False) context_node.reload() return HttpResponse("success") return HttpResponse("failure") return HttpResponse("None")
def create_edit_page(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False : group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id } available_nodes = collection.Node.find({'_type': u'GSystem', 'member_of': ObjectId(gst_page._id) }) nodes_list = [] for each in available_nodes: nodes_list.append(each.name) if node_id: page_node = collection.Node.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: page_node = collection.GSystem() if request.method == "POST": get_node_common_fields(request, page_node, group_id, gst_page) page_node.save() return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) else: if node_id: page_node,ver=get_page(request,page_node) context_variables['node'] = page_node context_variables['groupid']=group_id context_variables['group_id']=group_id context_variables['nodes_list'] = json.dumps(nodes_list) else: context_variables['nodes_list'] = json.dumps(nodes_list) return render_to_response("ndf/page_create_edit.html", context_variables, context_instance=RequestContext(request) )
def create_task(request, task_id, group_id): if task_id: task_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(task_id) }) edit_task_node = task_node else: task_node = node_collection.collection.GSystem() name = request.POST.get("name", "") content_org = request.POST.get("content_org", "") parent = request.POST.get("parent", "") Status = request.POST.get("Status", "") Start_date = request.POST.get("start_time", "") Priority = request.POST.get("Priority", "") Due_date = request.POST.get("end_time", "") Assignee = request.POST.get("Assignee", "") Estimated_time = request.POST.get("Estimated_time", "") watchers = request.POST.get("watchers", "") GST_TASK = node_collection.one({'_type': "GSystemType", 'name': 'Task'}) tag = "" field_value = [] file_name = (request.POST.get("files_name")) if not task_id: # create get_node_common_fields(request, task_node, group_id, GST_TASK) # Adding watchers to node's author_set if watchers: task_node.author_set = [] user_to_be_notified = [] for each_watchers in watchers.split(','): bx = User.objects.get(id=int(each_watchers)) if bx: task_node.author_set.append(bx.id) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) task_node.save(groupid=group_id) if parent: # prior node saving if not task_id: task_node.prior_node = [ObjectId(parent)] parent_object = node_collection.find_one({'_id': ObjectId(parent)}) parent_object.post_node = [task_node._id] parent_object.save(groupid=group_id) task_node.save(groupid=group_id) return task_node
def create_task(request,task_id,group_id): if task_id: task_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(task_id)}) edit_task_node = task_node else: task_node = node_collection.collection.GSystem() name = request.POST.get("name","") content_org = request.POST.get("content_org","") parent = request.POST.get("parent","") Status = request.POST.get("Status","") Start_date = request.POST.get("start_time", "") Priority = request.POST.get("Priority","") Due_date = request.POST.get("end_time", "") Assignee = request.POST.get("Assignee","") Estimated_time = request.POST.get("Estimated_time","") watchers = request.POST.get("watchers", "") GST_TASK = node_collection.one({'_type': "GSystemType", 'name': 'Task'}) tag="" field_value=[] file_name=(request.POST.get("files_name")) if not task_id: # create get_node_common_fields(request, task_node, group_id, GST_TASK) # Adding watchers to node's author_set if watchers: task_node.author_set = [] user_to_be_notified= [] for each_watchers in watchers.split(','): bx = User.objects.get(id=int(each_watchers)) if bx: task_node.author_set.append(bx.id) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) task_node.save(groupid=group_id) if parent: # prior node saving if not task_id: task_node.prior_node = [ObjectId(parent)] parent_object = node_collection.find_one({'_id': ObjectId(parent)}) parent_object.post_node = [task_node._id] parent_object.save(groupid=group_id) task_node.save(groupid=group_id) return task_node
def create_edit_quiz(request, group_id, node_id=None): """Creates/Edits quiz category. """ try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) context_variables = { 'title': gst_quiz.name, 'group_id': group_id, 'groupid': group_id } if node_id: quiz_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) if request.method == "POST": if node_id: quiz_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) else: quiz_node = node_collection.collection.GSystem() # get_node_common_fields(request, quiz_node, group_id, gst_quiz) quiz_node.save(is_changed=get_node_common_fields( request, quiz_node, group_id, gst_quiz), groupid=group_id) quiz_node.get_neighbourhood(quiz_node.member_of) # get_node_metadata(request, quiz_node,gst_quiz) #if teaches is required # teaches_list = request.POST.get('teaches_list','') # get the teaches list # if teaches_list !='': # teaches_list=teaches_list.split(",") # create_grelation_list(quiz_node._id,"teaches",teaches_list) # assesses_list = request.POST.get('assesses_list','') # get the assesses list # if assesses_list !='': # assesses_list=assesses_list.split(",") # create_grelation_list(quiz_node._id,"assesses",assesses_list) return HttpResponseRedirect( reverse('quiz_details', kwargs={ 'group_id': group_id, 'node_id': quiz_node._id })) else: if node_id: context_variables['node'] = quiz_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # context_variables['appId']=app._id return render_to_response("ndf/quiz_create_edit.html", context_variables, context_instance=RequestContext(request))
def create_edit_quiz(request, group_id, node_id=None): """Creates/Edits quiz category. """ ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False : group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass context_variables = { 'title': gst_quiz.name, 'group_id': group_id, 'groupid': group_id } if node_id: quiz_node = collection.Node.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: quiz_node = collection.GSystem() if request.method == "POST": get_node_common_fields(request, quiz_node, group_id, gst_quiz) quiz_node.save() return HttpResponseRedirect(reverse('quiz_details', kwargs={'group_id': group_id, 'app_id': quiz_node._id})) else: if node_id: context_variables['node'] = quiz_node context_variables['groupid'] = group_id context_variables['group_id']=group_id return render_to_response("ndf/quiz_create_edit.html", context_variables, context_instance=RequestContext(request) )
def create_edit(request, group_id, node_id = None): """Creates/Modifies details about the given quiz-item. """ ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False : group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass context_variables = { 'title': GST_COURSE.name, 'group_id': group_id, 'groupid':group_id } if node_id: course_node = collection.Node.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: course_node = collection.GSystem() if request.method == "POST": get_node_common_fields(request, course_node, group_id, GST_COURSE) course_node.save() return HttpResponseRedirect(reverse('course', kwargs={'group_id': group_id})) else: if node_id: context_variables['node'] = course_node context_variables['groupid']=group_id context_variables['group_id']=group_id return render_to_response("ndf/course_create_edit.html", context_variables, context_instance=RequestContext(request) )
def create_edit_quiz(request, group_id, node_id=None): """Creates/Edits quiz category. """ try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) context_variables = { 'title': gst_quiz.name, 'group_id': group_id, 'groupid': group_id } if node_id: quiz_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) if request.method == "POST": if node_id: quiz_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: quiz_node = node_collection.collection.GSystem() # get_node_common_fields(request, quiz_node, group_id, gst_quiz) quiz_node.save(is_changed=get_node_common_fields(request, quiz_node, group_id, gst_quiz),groupid=group_id) quiz_node.get_neighbourhood(quiz_node.member_of) # get_node_metadata(request, quiz_node,gst_quiz) #if teaches is required # teaches_list = request.POST.get('teaches_list','') # get the teaches list # if teaches_list !='': # teaches_list=teaches_list.split(",") # create_grelation_list(quiz_node._id,"teaches",teaches_list) # assesses_list = request.POST.get('assesses_list','') # get the assesses list # if assesses_list !='': # assesses_list=assesses_list.split(",") # create_grelation_list(quiz_node._id,"assesses",assesses_list) return HttpResponseRedirect(reverse('quiz_details', kwargs={'group_id': group_id, 'node_id': quiz_node._id})) else: if node_id: context_variables['node'] = quiz_node context_variables['groupid'] = group_id context_variables['group_id']=group_id # context_variables['appId']=app._id return render_to_response("ndf/quiz_create_edit.html", context_variables, context_instance=RequestContext(request) )
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None # if ObjectId.is_valid(group_id) is False : # group_ins = node_collection.one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) ''' app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name ''' app_set = "" app_collection_set = [] title = "" session_of="" module="" Add="" announced_course ="" batch ="" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" '''if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type Event_Types = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) ''' group_inverse_rel_id = [] Group_type=node_collection.one({'_id':ObjectId(group_id)}) for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}}) Eventtype='Eventtype' if Group_name: if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype='CollegeEvents' else: Eventtype='Eventtype' Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"}) Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1}) app_collection_set=[] if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) iteration=request.POST.get("iteration","") if iteration == "": iteration=1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) title = event_gst.name event_gs = node_collection.collection.GSystem() event_gs.member_of.append(event_gst._id) if app_set_instance_id: event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(event_gs)#.property_order if request.method == "POST": # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name","")) == "": if i>0: field_value=request.POST.get('start_time'+"_"+str(i),'') else: field_value = request.POST.get('start_time','') if event_gst.name == "Exam": name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value else: name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value event_gs.name=name event_gs.save(is_changed=is_changed,groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key('_id'): field_instance = node_collection.one({'_id': field_set['_id']}) field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance["validators"]: if i>0: field_value=request.POST.get(field_instance["name"]+"_"+str(i)) else: field_value = request.POST[field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value) # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name else: field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # if isinstance(event_gs_triple_instance, list): # print "\n" # for each in event_gs_triple_instance: # print " event_gs_triple_instance: ", each._id, " -- ", each.name # print "\n" # else: # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i==( (int(iteration))-1): #code to send mail to every one return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id})) else: to_user_list = [] event_organizer_str = "" event_coordinator_str = "" event_organized_by = [] event_coordinator = [] event_node = node_collection.one({'_id':ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('event_organised_by') in i.keys(): event_organized_by = i['event_organised_by'] if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] if unicode('event_coordinator') in i.keys(): event_coordinator = i['event_coordinator'] event_url = "/"+str(group_id)+"/event/"+str(app_set_id) +"/"+str(event_node._id) site = Site.objects.get(pk=1) site = site.name.__str__() event_link = "http://" + site + event_url event_organized_by_cur = node_collection.find({"_id":{'$in':event_organized_by}}) event_coordinator_cur = node_collection.find({"_id":{'$in':event_coordinator}}) for i in event_coordinator_cur: event_coordinator_str = event_coordinator_str + i.name + " " for i in event_organized_by_cur: event_organizer_str = event_coordinator_str + i.name + " " for j in event_attendees: auth = node_collection.one({"_id":ObjectId(j)}) user_obj = User.objects.get(id=auth.created_by) if user_obj not in to_user_list: to_user_list.append(user_obj) render_label = render_to_string( "notification/label.html", { "sender": "metaStudio", "activity": "Event Created", "conjunction": "-" }) if event_organized_by: msg_string = "\n Event is organized by " + str ( event_organizer_str ) else: msg_string = "" notification.create_notice_type(render_label,"Invitation for Event"+ " " + str(event_node.name) + msg_string + "\n Event will be co-ordinated by " +str (event_coordinator_str) + "\n- Please click [[" + event_link + "][here]] to view the details of the event" , "notification") notification.send(to_user_list, render_label, {"from_user":"******"}) return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id})) event_attendees = request.POST.getlist('has_attendees','') event_gs.get_neighbourhood(event_gs.member_of) course=[] val=False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])}) batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])}) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])}) if unicode('session_of') in i.keys(): session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])}) module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}}) event_gs.event_coordinator Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"}) if Mis_admin: Mis_admin_list=Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add="Allow" else: Add= "Stop" else: Add="Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template="ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list, 'Add':Add } if app_set_instance_id: event_detail={} events={} if event_gs.event_coordinator: event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id) events["cordinator"]=event_detail if announced_course: event_detail["course"]=str(announced_course.name) event_detail["course_id"]=str(announced_course._id) events["course"]=event_detail event_detail={} if batch: event_detail["batchname"]=str(batch.name) event_detail["batchid"]=str(batch._id) events["batch"]=event_detail event_detail={} if session_of: event_detail["sessionname"]=str(session_of.name) event_detail["sessionid"]=str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str(i['course_structure_minutes']) events["session"]=event_detail event_detail={} if module: event_detail["Modulename"]=str(module.name) event_detail["Moduleid"]=str(module._id) events["Module"]=event_detail context_variables['node'] = event_gs context_variables['edit_details']=events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance = RequestContext(request) )
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None try: group_id = ObjectId(group_id) #group_id is a valid ObjectId except: group_name, group_id = get_group_name_id(group_id) #instead of group_id the name of the object is passed via URL to the function group_obj = node_collection.one({'_id': group_id}) app_set = "" title = "" #Stores the name of the type of event such as Meeting, Inauguration, etc. session_of="" module="" Add="" announced_course ="" batch ="" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" group_inverse_rel_id = [] Group_type=node_collection.one({'_id':ObjectId(group_id)}) #instance of the group object in which the event is created e.g. "home" is a group for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}}) Eventtype='Eventtype' if Group_name: if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype='CollegeEvents' else: Eventtype='Eventtype' Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"}) Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1}) #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ... app_collection_set=[] #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) iteration=request.POST.get("iteration","") if iteration == "": iteration=1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) #GSystemType Object for the event corresponding to app_set_id e.g. Meeting title = event_gst.name event_gs = node_collection.collection.GSystem() #create a new GSystem Object for the Event event_gs.member_of.append(event_gst._id) #event_gs is a member_of event_gst if app_set_instance_id: #app_set_instance_id is the objectid of the event object which is already created event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(event_gs) #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc.. if request.method == "POST": # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name","")) == "": if i>0: field_value=request.POST.get('start_time'+"_"+str(i),'') else: field_value = request.POST.get('start_time','') # print "----------------Field Value-----------" # print field_value if event_gst.name == "Exam": name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value else: name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value # print "-----------------Name------------------" # print name event_gs.name=name # if request.POST.get("is_bigbluebutton") == unicode("Yes"): # event_gs.is_bigbluebutton = True # else: # event_gs.is_bigbluebutton = False event_gs.save(is_changed=is_changed,groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" check_attendee = True # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key('_id'): #Implies field_set is not a basefield but is an AT/RT field_instance = node_collection.one({'_id': field_set['_id']})#field_instance is an instance for AT or RT e.g. start_time field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] #data type of AT/RT e.g. datetime.datetime for start_time # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type open_event = False if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance["validators"]: if i>0: field_value=request.POST.get(field_instance["name"]+"_"+str(i)) else: field_value = request.POST[field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value) # print "--------------------------------------------------------------------------------------------------" # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name if field_instance["name"] == 'open_event': open_event = field_value else: #field_instance_type == RelationType field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate(field_value_list): try: field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") except: field_value = parse_template_data(ObjectId, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: if field_instance["name"] == "has_attendees" and open_event == "False": send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs) else: event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # End of for loop on property_order_list # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i==( (int(iteration))-1): #code to send mail to every one return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id})) else: event_attendees = [] event_node = node_collection.one({'_id':ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs, event_attendees) return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id})) event_attendees = request.POST.getlist('has_attendees','') event_gs.get_neighbourhood(event_gs.member_of) course=[] val=False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])}) batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])}) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])}) if unicode('session_of') in i.keys(): session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])}) module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}}) event_gs.event_coordinator Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"}) if Mis_admin: Mis_admin_list=Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add="Allow" else: Add= "Stop" else: Add="Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template="ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list, 'Add':Add } if app_set_instance_id: event_detail={} events={} if event_gs.event_coordinator: event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id) events["cordinator"]=event_detail if announced_course: event_detail["course"]=str(announced_course.name) event_detail["course_id"]=str(announced_course._id) events["course"]=event_detail event_detail={} if batch: event_detail["batchname"]=str(batch.name) event_detail["batchid"]=str(batch._id) events["batch"]=event_detail event_detail={} if session_of: event_detail["sessionname"]=str(session_of.name) event_detail["sessionid"]=str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str(i['course_structure_minutes']) events["session"]=event_detail event_detail={} if module: event_detail["Modulename"]=str(module.name) event_detail["Moduleid"]=str(module._id) events["Module"]=event_detail context_variables['node'] = event_gs context_variables['edit_details']=events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance = RequestContext(request) )
def create_edit_term(request, group_id, node_id=None): # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) context_variables = { 'title': title, 'group_id': group_id, 'groupid': group_id } # To list all term instances terms_list = node_collection.find({ '_type': 'GSystem', 'member_of': { '$all': [ObjectId(term_GST._id), ObjectId(topic_GST._id)] }, 'group_set': ObjectId(group_id) }).sort('name', 1) nodes_list = [] for each in terms_list: nodes_list.append(str((each.name).strip().lower())) if node_id: term_node = node_collection.one({'_id': ObjectId(node_id)}) else: term_node = node_collection.collection.GSystem() if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) term_node.save(is_changed=get_node_common_fields( request, term_node, group_id, term_GST), groupid=group_id) get_node_metadata(request, term_node, term_GST) return HttpResponseRedirect( reverse('term_details', kwargs={ 'group_id': group_id, 'node_id': term_node._id })) else: if node_id: term_node, ver = get_page(request, term_node) term_node.get_neighbourhood(term_node.member_of) context_variables['node'] = term_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id context_variables['nodes_list'] = json.dumps(nodes_list) else: context_variables['nodes_list'] = json.dumps(nodes_list) return render_to_response("ndf/term_create_edit.html", context_variables, context_instance=RequestContext(request))
def create_entries(request, group_id): ''' for creating a new bibtex entry_list ''' ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False : group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass ''' for retreiving the fields of a particular bibtex entry ''' num = int(request.GET.get('num')) entry=Bibtex_entries[num] for name, value in entry.iteritems(): title=name list_item=value GST_BIBTEX = collection.Node.one({'_type': 'GSystemType', 'name': title}) GST_ENTRY=collection.Node.one({'_type':'AttributeType','name':'BibTex_entry'}) GST_LIST=collection.Node.one({'_type':'AttributeType','name':'entry_list'}) GST_CITATION=collection.Node.one({'_type':'AttributeType','name':'Citation'}) context_variables = { 'title': title, 'group_id': group_id, 'groupid': group_id, 'list_item':list_item, 'num':num } entry_node = collection.GSystem() cite="" i=0 value="" if request.method == "POST": name=request.POST.get("name") entry_node.name=name citation_key=request.POST.get("citation_key") var="@"+title+"{"+citation_key value += "name$"+name+"%citation_key$"+citation_key+"%" for each in list_item: c = request.POST.get(each,"") var += " , "+each+" = "+" { "+c+" }" value += each + "$" + c + "%" i = i+1 if (each == 'author' and c!= ""): cite += c +"." if(each == 'title' and c!= ""): cite += c+'.' if(each == 'year' and c != ""): cite += "("+c+") " if(each=='publisher' and c!=""): cite += "publisher:"+ c + "," if(each == 'volume' and c!=""): cite += "volume:"+c +"," if(each == 'edition' and c!=""): cite += "edition:"+c+"," if(each == 'pages' and c!=""): cite += "page "+c+"," var +="}" get_node_common_fields(request,entry_node,group_id,GST_BIBTEX) entry_node.status=u'PUBLISHED' entry_node.save() ''' creating a GAttribute of AttributeType BibTex_entry for the already created GSystem ''' GST_current=collection.Node.one({'name':name,'member_of':title}) Bibtex_entry=collection.GAttribute() Bibtex_entry.name=unicode(name) Bibtex_entry.subject=ObjectId(entry_node._id) Bibtex_entry.attribute_type=GST_ENTRY Bibtex_entry.object_value=unicode(var) Bibtex_entry.save() ''' creating a GAttribute of AttributeType Citation for the already created GSystem ''' cite_key=collection.GAttribute() cite_key.name=unicode(name) cite_key.subject=ObjectId(entry_node._id) cite_key.attribute_type=GST_CITATION cite_key.object_value=unicode(cite) cite_key.save() ''' creating a GAttribute of AttributeType entry_list for the already created GSystem ''' entry_list=collection.GAttribute() entry_list.name=unicode(name) entry_list.subject=ObjectId(entry_node._id) entry_list.attribute_type=GST_LIST entry_list.object_value=unicode(value) entry_list.save() return HttpResponseRedirect(reverse('view_entry', kwargs={'group_id': group_id, 'node_id': GST_BIBTEX._id})) else: return render_to_response("ndf/create_edit_entries.html", context_variables, context_instance=RequestContext(request))
def create_edit_page(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass group_name, group_id = get_group_name_id(group_id) ce_id = request.GET.get('course_event_id', '') blog_type = request.GET.get('blog_type', '') res = request.GET.get('res', '') program_res = request.GET.get('program_res', '') context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id, 'ce_id': ce_id, 'res': res, 'program_res': program_res, 'blog_type': blog_type } group_obj = node_collection.one({'_id': ObjectId(group_id)}) available_nodes = node_collection.find({ '_type': u'GSystem', 'member_of': ObjectId(gst_page._id), 'group_set': ObjectId(group_id), '_id': { '$ne': ObjectId(node_id) } }) nodes_list = [] thread = None url_name = "/home" # for each in available_nodes: # nodes_list.append(str((each.name).strip().lower())) # loop replaced by a list comprehension node_list = [str((each.name).strip().lower()) for each in available_nodes] # print "available_nodes: ", node_list if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) page_name = request.POST.get('name', '') # print "====== page_name: ", page_name if page_name.strip().lower() in node_list and not node_id: new_page = False return render_to_response("error_base.html", { 'message': 'Page with same name already exists in the group!' }, context_instance=RequestContext(request)) elif node_id: new_page = False page_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) else: new_page = True page_node = node_collection.collection.GSystem() # page_type = request.POST.getlist("type_of",'') ce_id = request.POST.get("ce_id", '') blog_type = request.POST.get('blog_type', '') res = request.POST.get("res", '') program_res = request.POST.get('program_res', '') # we are fetching the value of release_response flag # if this is set, it means, we can proceed to create a thread node # for the current page node. thread_create_val = request.POST.get("thread_create", '') # print "\n\n thread_create_val", thread_create_val # print "\n\n request.POST === ",request.POST # raise Exception("demo") # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) # print "\n\n help_info_page === ",help_info_page #program_res and res are boolean values if program_res: program_res = eval(program_res) if res: res = eval(res) if blog_type: blog_type = eval(blog_type) # if page_type: # objid= page_type[0] # if not ObjectId(objid) in page_node.type_of: # page_type1=[] # page_type1.append(ObjectId(objid)) # page_node.type_of = page_type1 # page_node.type_of page_node.save(is_changed=get_node_common_fields( request, page_node, group_id, gst_page)) # if course event grp's id is passed, it means # its a blog page added in notebook and hence set type_of field as "Blog page" # print "\n\n blog_type---",blog_type if blog_type: blogpage_gst = node_collection.one({ '_type': "GSystemType", 'name': "Blog page" }) page_node.type_of = [blogpage_gst._id] elif GSTUDIO_SITE_NAME == "NROER" and "Author" in group_obj.member_of_names_list: infopage_gst = node_collection.one({ '_type': "GSystemType", 'name': "Info page" }) page_node.type_of = [infopage_gst._id] # if the page created is as a resource in course or program event, # set status to PUBLISHED by default # one major reason for this, ONLY published nodes can be replicated. if res or program_res or ce_id: page_node.status = u"PUBLISHED" page_node.save() # if page is created in program event, add page_node to group's collection set if program_res: group_obj = node_collection.one({'_id': ObjectId(group_id)}) group_obj.collection_set.append(page_node._id) group_obj.save() discussion_enable_at = node_collection.one({ "_type": "AttributeType", "name": "discussion_enable" }) if thread_create_val == "Yes" or blog_type: create_gattribute(page_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request, group_id, page_node) else: create_gattribute(page_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if "None" not in help_info_page: has_help_rt = node_collection.one({ '_type': "RelationType", 'name': "has_help" }) try: help_info_page = map(ObjectId, help_info_page) create_grelation(page_node._id, has_help_rt, help_info_page) page_node.reload() except Exception as invalidobjectid: # print invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(page_node._id, "has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id", "") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=page_node._id, node_id=each_grel_id, deletion_type=0) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg # To fill the metadata info while creating and editing page node metadata = request.POST.get("metadata_info", '') if "CourseEventGroup" in group_obj.member_of_names_list and blog_type: if new_page: # counter_obj = Counter.get_counter_obj(request.user.id,ObjectId(group_id)) # # counter_obj.no_notes_written=counter_obj.no_notes_written+1 # counter_obj['page']['blog']['created'] += 1 # # counter_obj.course_score += GSTUDIO_NOTE_CREATE_POINTS # counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS # counter_obj.last_update = datetime.datetime.now() # counter_obj.save() active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime( request.user.id, datetime.datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys( active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur( active_user_ids_list, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['page']['blog']['created'] += 1 each_counter_obj[ 'group_points'] += GSTUDIO_NOTE_CREATE_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save() return HttpResponseRedirect( reverse('course_notebook_tab_note', kwargs={ 'group_id': group_id, 'tab': 'my-notes', 'notebook_id': page_node._id })) if ce_id or res or program_res: url_name = "/" + group_name + "/" + str(page_node._id) if ce_id: # url_name = "/" + group_name + "/#journal-tab" url_name = "/" + group_name if res or program_res: url_name = "/" + group_name + "/?selected=" + str( page_node._id) + "#view_page" # print "\n\n url_name---",url_name return HttpResponseRedirect(url_name) if metadata: # Only while metadata editing if metadata == "metadata": if page_node: get_node_metadata(request, page_node, is_changed=True) # End of filling metadata return HttpResponseRedirect( reverse('page_details', kwargs={ 'group_id': group_id, 'app_id': page_node._id })) else: if node_id: page_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) #page_node,ver=get_page(request,page_node) page_node.get_neighbourhood(page_node.member_of) context_variables['node'] = page_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # fetch Page instances # Page_node = node_collection.find_one({'_type':"GSystemType","name":"Page"}) page_instances = node_collection.find({"type_of": gst_page._id}) page_ins_list = [i for i in page_instances] context_variables['page_instance'] = page_ins_list context_variables['nodes_list'] = json.dumps(nodes_list) # print "\n\n context_variables----\n",context_variables return render_to_response("ndf/page_create_edit.html", context_variables, context_instance=RequestContext(request))
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given person-type. """ auth = None if ObjectId.is_valid(group_id) is False: group_ins = node_collection.one({'_type': "Group", "name": group_id}) auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else: auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if auth: group_id = str(auth._id) else: pass app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" person_gst = None person_gs = None college_node = None college_id = None student_enrollment_code = u"" create_student_enrollment_code = False existing_colg = [] registration_date = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) agency_type = auth.agency_type agency_type_node = node_collection.one( { '_type': "GSystemType", 'name': agency_type }, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append( node_collection.one({"_id": eachset}, { '_id': 1, 'name': 1, 'type_of': 1 })) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) college_node = node_collection.one( { "_id": ObjectId(group_id), "relation_set.group_of": { "$exists": True } }, {"relation_set.group_of": 1}) if app_set_id: person_gst = node_collection.one( { '_type': "GSystemType", '_id': ObjectId(app_set_id) }, { 'name': 1, 'type_of': 1 }) template = "ndf/" + person_gst.name.strip().lower().replace( ' ', '_') + "_create_edit.html" title = person_gst.name person_gs = node_collection.collection.GSystem() person_gs.member_of.append(person_gst._id) if app_set_instance_id: person_gs = node_collection.one({ '_type': "GSystem", '_id': ObjectId(app_set_instance_id) }) property_order_list = get_property_order_with_value( person_gs) #.property_order if request.method == "POST": if person_gst.name == "Student" and "_id" not in person_gs: create_student_enrollment_code = True # [A] Save person-node's base-field(s) is_changed = get_node_common_fields(request, person_gs, group_id, person_gst) if is_changed: # Remove this when publish button is setup on interface person_gs.status = u"PUBLISHED" person_gs.save(is_changed=is_changed, groupid=group_id) for each_rel in person_gs.relation_set: if each_rel and "officer_incharge_of" in each_rel: existing_colg = each_rel["officer_incharge_of"] if college_node: mis_admin = node_collection.one( { "_type": "Group", "name": "MIS_admin" }, {"_id": 1}) node_collection.collection.update( {"_id": person_gs._id}, {"$addToSet": { "group_set": mis_admin._id }}, upsert=False, multi=False) # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one( {'_id': field_set['_id']}) fi_name = field_instance["name"] field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used user_id = request.user.id if fi_name in request.FILES: field_value = request.FILES[fi_name] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = person_gs.name + " -- " + field_instance[ "altnames"] content_org = "" tags = "" field_value = save_file( field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes if fi_name in request.POST: field_value = request.POST[fi_name] # field_instance_type = "GAttribute" if fi_name in [ "12_passing_year", "degree_passing_year" ]: #, "registration_year"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%Y") elif fi_name in ["dob", "registration_date"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y") registration_date = field_value else: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: person_gs_triple_instance = create_gattribute( person_gs._id, node_collection.collection.AttributeType( field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get( fi_name, "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads( field_value_list) else: field_value_list = request.POST.getlist( fi_name) else: field_value_list = request.POST.getlist( fi_name) if META_TYPE[ 3] in field_instance.member_of_names_list: # If Binary relationship found # [id, id, ...] # field_instance_type = "GRelation" for i, field_value in enumerate( field_value_list): field_value = parse_template_data( field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value else: # Relationship Other than Binary one found; e.g, Triadic # [[id, id, ...], [id, id, ...], ...] # field_instance_type = "GRelation" for i, field_value_inner_list in enumerate( field_value_list): for j, field_value in enumerate( field_value_inner_list): field_value = parse_template_data( field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M" ) field_value_list[i][j] = field_value person_gs_triple_instance = create_grelation( person_gs._id, node_collection.collection.RelationType( field_instance), field_value_list) # Setting enrollment code for student node only while creating it if create_student_enrollment_code: # Create enrollment code for student node only while registering a new node for rel in college_node.relation_set: if rel and "group_of" in rel: college_id = rel["group_of"][0] student_enrollment_code = get_student_enrollment_code( college_id, person_gs._id, registration_date, ObjectId(group_id)) enrollment_code_at = node_collection.one({ "_type": "AttributeType", "name": "enrollment_code" }) try: ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code) except Exception as e: print "\n StudentEnrollmentCreateError: " + str(e) + "!!!" # [C] Code to link GSystem Node and Author node via "has_login" relationship; # and Subscribe the Author node to College group if user "Program Officer" person_gs.reload() auth_node = None for attr in person_gs.attribute_set: if "email_id" in attr: if attr["email_id"]: auth_node = node_collection.one({ '_type': "Author", 'email': attr["email_id"].lower() }) break if auth_node: has_login_rt = node_collection.one({ '_type': "RelationType", 'name': "has_login" }) if has_login_rt: # Linking GSystem Node and Author node via "has_login" relationship; gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id) # Set author_agency field's value of author node as "Program Officer" # Required to identify at time of log-in in order to display # required modules defined for Program Officers under MIS GApp if auth_node.agency_type != u"Program Officer": auth_node.agency_type = u"Program Officer" auth_node.save(groupid=group_id) if "Program Officer" in person_gs.member_of_names_list: # If Person node (GSystem) is of Program Officer type # then only go for subscription college_id_list = [] # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of") for rel in person_gs.relation_set: if "officer_incharge_of" in rel: if rel["officer_incharge_of"]: for college_id in rel["officer_incharge_of"]: if college_id not in college_id_list: college_id_list.append(college_id) break # break outer-loop (of relation_set) if college_id_list: # If College's ObjectId exists (list as PO might be assigned to more than one college) # Then prepare a list of their corresponding private group(s) (via "has_group") college_cur = node_collection.find( {'_id': { '$in': college_id_list }}, {'relation_set.has_group': 1}) college_group_id_list = [] for college in college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][ 0] not in college_group_id_list: college_group_id_list.append( rel["has_group"][0]) break # break inner-loop (college.relation_set) if college_group_id_list: # If college-group list exists # Then update their group_admin field (append PO's created_by) res = node_collection.collection.update( {'_id': { '$in': college_group_id_list }}, { '$addToSet': { 'group_admin': auth_node.created_by } }, upsert=False, multi=True) old_college_id_list = [] if existing_colg: if len(existing_colg) > len(college_id_list): for each_colg_id in existing_colg: if each_colg_id not in college_id_list: old_college_id_list.append(each_colg_id) old_college_cur = node_collection.find( {'_id': { '$in': old_college_id_list }}, {'relation_set.has_group': 1}) old_college_group_id_list = [] for college in old_college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][ 0] not in old_college_group_id_list: old_college_group_id_list.append( rel["has_group"][0]) break # break inner-loop (college.relation_set) if old_college_group_id_list: # If college-group list exists # Then update their group_admin field (remove PO's created_by) res = node_collection.collection.update( { '_id': { '$in': old_college_group_id_list }, '$or': [{ 'group_admin': auth_node.created_by }, { 'author_set': auth_node.created_by }] }, { '$pull': { 'group_admin': auth_node.created_by, 'author_set': auth_node.created_by } }, upsert=False, multi=True) # The code below is commented as the college groups are PRIVATE. # for rel in person_gs.relation_set: # if rel and "officer_incharge_of" in rel: # pass # else: # node_collection.collection.update({'_id': auth_node._id}, # {'$set': {'agency_type': u"Other"}}, # upsert=False, multi=False # ) # Its purpose is to change the agency type back to Other auth_node.reload() # if person_gst.name != "Student": # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) # else: return HttpResponseRedirect( reverse('mis:mis_app_instance_detail', kwargs={ 'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id, "app_set_instance_id": unicode(person_gs._id) })) # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) default_template = "ndf/person_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list } if person_gst and person_gst.name in [ "Voluntary Teacher", "Master Trainer" ]: nussd_course_type = node_collection.one( { '_type': "AttributeType", 'name': "nussd_course_type" }, { '_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1 }) if nussd_course_type["data_type"] == "IS()": # Below code does little formatting, for example: # data_type: "IS()" complex_value: [u"ab", u"cd"] dt: # "IS(u'ab', u'cd')" dt = "IS(" for v in nussd_course_type.complex_data_type: dt = dt + "u'" + v + "'" + ", " dt = dt[:(dt.rfind(", "))] + ")" nussd_course_type["data_type"] = dt nussd_course_type["data_type"] = eval(nussd_course_type["data_type"]) nussd_course_type["value"] = None context_variables['nussd_course_type'] = nussd_course_type if app_set_instance_id: person_gs.get_neighbourhood(person_gs.member_of) if "trainer_teaches_course_in_college" in person_gs: l = [] for each_course_college in person_gs.trainer_teaches_course_in_college: # Fetch Course Type (i.e. nussd_course_type) ct = "" for each_attr in each_course_college[0].attribute_set: if "nussd_course_type" in each_attr and each_attr: ct = each_attr["nussd_course_type"] break univ_name = "" for each_rel in each_course_college[1].relation_set: if "college_affiliated_to" in each_rel and each_rel: univ = node_collection.find_one({ "_id": { "$in": each_rel["college_affiliated_to"] } }) univ_name = univ.name if univ else "" l.append((ct, each_course_college[0].name, each_course_college[1].name, each_course_college[0]._id.__str__(), each_course_college[1]._id.__str__(), univ_name)) if l: person_gs.trainer_teaches_course_in_college = l context_variables['node'] = person_gs try: return render_to_response([template, default_template], context_variables, context_instance=RequestContext(request)) except TemplateDoesNotExist as tde: error_message = "\n PersonCreateEditViewError: This html template (" + str( tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def data_review_save(request, group_id): ''' Method to save each and every data-row edit of data review app ''' userid = request.user.pk try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_obj = node_collection.one({"_id": ObjectId(group_id)}) node_oid = request.POST.get("node_oid", "") node_details = request.POST.get("node_details", "") node_details = json.loads(node_details) # print "node_details : ", node_details # updating some key names of dictionary as per get_node_common_fields. node_details["lan"] = node_details.pop("language") node_details["prior_node_list"] = node_details.pop("prior_node") node_details["login-mode"] = node_details.pop("access_policy") status = node_details.pop("status") # node_details["collection_list"] = node_details.pop("collection") for future use # Making copy of POST QueryDict instance. # To make it mutable and fill in node_details value/s. post_req = request.POST.copy() # removing node_details dict from req post_req.pop('node_details') # adding values to post req post_req.update(node_details) # overwriting request.POST with newly created QueryDict instance post_req request.POST = post_req # print "\n---\n", request.POST, "\n---\n" copyright = request.POST.get('copyright', '') file_node = node_collection.one({"_id": ObjectId(node_oid)}) if request.method == "POST": edit_summary = [] file_node_before = file_node.copy() # copying before it is getting modified is_changed = get_node_common_fields(request, file_node, group_id, GST_FILE) for key, val in file_node_before.iteritems(): if file_node_before[key] != file_node[key]: temp_edit_summ = {} temp_edit_summ["name"] = "Field: " + key temp_edit_summ["before"] = file_node_before[key] temp_edit_summ["after"] = file_node[key] edit_summary.append(temp_edit_summ) # to fill/update attributes of the node and get updated attrs as return ga_nodes = get_node_metadata(request, file_node, is_changed=True) if len(ga_nodes): is_changed = True # adding the edit attribute name in summary for each_ga in ga_nodes: temp_edit_summ = {} temp_edit_summ["name"] = "Attribute: " + each_ga["node"]["attribute_type"]["name"] temp_edit_summ["before"] = each_ga["before_obj_value"] temp_edit_summ["after"] = each_ga["node"]["object_value"] edit_summary.append(temp_edit_summ) teaches_list = request.POST.get('teaches', '') # get the teaches list prev_teaches_list = request.POST.get("teaches_prev", "") # get the before-edit teaches list # check if teaches list exist means nodes added/removed for teaches relation_type # also check for if previous teaches list made empty with prev_teaches_list if (teaches_list != '') or prev_teaches_list: teaches_list = teaches_list.split(",") if teaches_list else [] teaches_list = [ObjectId(each_oid) for each_oid in teaches_list] relation_type_node = node_collection.one({'_type': "RelationType", 'name':'teaches'}) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes] if gr_nodes else [] prev_teaches_list = prev_teaches_list.split(",") if prev_teaches_list else [] prev_teaches_list = [ObjectId(each_oid) for each_oid in prev_teaches_list] if len(gr_nodes_oid_list) == len(prev_teaches_list) and set(gr_nodes_oid_list) == set(prev_teaches_list): pass else: rel_nodes = triple_collection.find({'_type': "GRelation", 'subject': file_node._id, 'relation_type': relation_type_node._id }) rel_oid_name = {} for each in rel_nodes: temp = {} temp[each.right_subject] = each.name rel_oid_name.update(temp) is_changed = True temp_edit_summ = {} temp_edit_summ["name"] = "Relation: Teaches" temp_edit_summ["before"] = [rel_oid_name[each_oid].split(" -- ")[2] for each_oid in prev_teaches_list] temp_edit_summ["after"] = [rel_oid_name[each_oid].split(" -- ")[2] for each_oid in gr_nodes_oid_list] edit_summary.append(temp_edit_summ) assesses_list = request.POST.get('assesses_list','') if assesses_list != '': assesses_list = assesses_list.split(",") assesses_list = [ObjectId(each_oid) for each_oid in assesses_list] relation_type_node = node_collection.one({'_type': "RelationType", 'name':'assesses'}) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes] if len(gr_nodes_oid_list) == len(teaches_list) and set(gr_nodes_oid_list) == set(teaches_list): pass else: is_changed = True # changing status to draft even if attributes/relations are changed if is_changed: file_node.status = unicode("DRAFT") file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) # checking if user is authenticated to change the status of node if status and ((group_obj.is_gstaff(request.user)) or (userid in group_obj.author_set)): if file_node.status != status: file_node.status = unicode(status) file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) is_changed = True if is_changed: file_node.save(groupid=group_id) # print edit_summary return HttpResponse(file_node.status)
def theme_topic_create_edit(request, group_id, app_id=None, app_set_id=None): app_collection_set = [] nodes_dict = [] create_edit = True themes_hierarchy = False themes_list_items = "" title = "" node = "" theme_topic_node = "" drawers = None drawer = None nodes_list = [] parent_nodes_collection = "" app = collection.Node.find_one({"_id":ObjectId(app_id)}) if app: for each in app.collection_set: app_set = collection.Node.find_one({"_id":each}) app_collection_set.append({"id":str(app_set._id),"name":app_set.name}) if request.method == "POST": app_GST = collection.Node.find_one({"_id":ObjectId(app_set_id)}) if app_GST: create_edit = True themes_list_items = "" root_themes = [] name = request.POST.get('name') collection_list = request.POST.get('collection_list','') # To find the root nodes to maintain the uniquness while creating and editing themes nodes = collection.Node.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) if app_GST.name == "Theme" or app_GST.name == "Topic": # For creating new themes & Topics themes_list_items = False create_edit = False themes_hierarchy = True if name: if not name.upper() in (theme_name.upper() for theme_name in root_themes): theme_topic_node = collection.GSystem() get_node_common_fields(request, theme_topic_node, group_id, app_GST) theme_topic_node.save() # This will return to Themes Hierarchy if theme_GST: node = theme_GST else: # For edititng themes themes_list_items = False create_edit = False themes_hierarchy = True theme_topic_node = collection.Node.one({'_id': ObjectId(app_GST._id)}) if theme_GST._id in app_GST.member_of: if name: if not name.upper() in (theme_name.upper() for theme_name in root_themes): get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save() # For storing and maintaning collection order theme_topic_node.collection_set = [] if collection_list != '': collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if collection.Node.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save() # End of storing collection title = theme_GST.name # This will return to Themes Hierarchy if theme_GST: node = theme_GST elif topic_GST._id in app_GST.member_of: get_node_common_fields(request, theme_topic_node, group_id, topic_GST) theme_topic_node.save() title = topic_GST.name node = theme_topic_node else: app_node = None nodes_list = [] app_GST = collection.Node.find_one({"_id":ObjectId(app_set_id)}) if app_GST: # For adding new Theme & Topic if app_GST.name == "Theme" or app_GST.name == "Topic": title = app_GST.name node = "" root_themes = [] # To find the root nodes to maintain the uniquness while creating new themes nodes = collection.Node.find({'member_of': {'$all': [app_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes = json.dumps(root_themes) nodes_list = root_themes # End of finding unique root level Themes else: # For editing theme & topic if theme_GST._id in app_GST.member_of: title = theme_GST.name node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "Theme" drawers = get_drawers(group_id, node._id, node.collection_set, checked) drawer = drawers['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme name nodes = collection.Node.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = collection.Node.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) # End of finding unique theme names for editing name # For adding a sub-themes and maintianing their uniqueness within their context for each in app_GST.collection_set: sub_theme = collection.Node.one({'_id': ObjectId(each) }) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes elif topic_GST._id in app_GST.member_of: title = topic_GST.name node = app_GST return render_to_response("ndf/theme.html", {'app_collection_set':app_collection_set, 'group_id': group_id,'groupid': group_id, 'drawer': drawer, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy,'app_id': app_id, 'nodes_list': nodes_list,'title': title,'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items,'nodes':nodes_dict },context_instance = RequestContext(request) )
def update(request,rt_list,at_list,task_node,group_id,group_name): file_id=(request.POST.get("files")) file_name=(request.POST.get("files_name")) user_to_be_notified = [] assignee_list = [] change_list = [] for each in rt_list: rel_type_node = node_collection.one({'_type': "RelationType", 'name': each}) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value old_value = [] for rel in task_node.relation_set: for k in rel: if rel_type_node.name == k: vals_cur = node_collection.find({'_id': {'$in': rel[k]}}, {'name': 1}) for v_node in vals_cur: old_value.append(v_node.name) break new_value = [] vals_cur = node_collection.find({'_id': {'$in': field_value_list}}, {'name': 1}) for v_node in vals_cur: new_value.append(v_node.name) break if old_value != new_value: change_list.append(each.encode('utf8') + ' changed from ' + ", ".join(old_value) + ' to ' + ", ".join(new_value)) # updated details task_gs_triple_instance = create_grelation(task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) task_node.reload() for each in at_list: if request.POST.get(each, ""): attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': each}) attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id}) if each == "Assignee": field_value = request.POST.getlist(each, "") for i, val in enumerate(field_value): field_value[i] = int(val) assignee_list_id = field_value for eachuser in assignee_list_id: bx = User.objects.get(id=int(eachuser)) if bx: if bx.username not in assignee_list: assignee_list.append(bx.username) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data(eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) if attr: # already attribute exist if not attr.object_value == field_value: # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details if attributetype_key["data_type"] == "datetime.datetime": change_list.append(each.encode('utf8')+' changed from ' + attr.object_value.strftime("%d/%m/%Y") + ' to ' + field_value.strftime("%d/%m/%Y")) # updated details else: change_list.append(each.encode('utf8')+' changed from ' + str(attr.object_value) + ' to ' + str(field_value)) # updated details attr.object_value = field_value attr.save(groupid=group_id) else: # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each}) # newattribute = triple_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = request.POST.get(each,"") # newattribute.object_value = field_value # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, field_value) # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details change_list.append(each.encode('utf8')+' set to '+str(field_value)) # updated details elif each == 'Upload_Task': attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': 'Upload_Task'}) attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id}) if attr: value=get_file_node(attr.object_value) change_list.append(each.encode('utf8')+' changed from '+str(value).strip('[]')+' to '+str(file_name)) # attr.object_value=file_id # attr.save() ga_node = create_gattribute(attr.subject, attributetype_key, file_id) else: # newattribute = node_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = file_id # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, file_id) change_list.append(each.encode('utf8')+' set to '+file_name.encode('utf8')) # updated details # userobj = User.objects.get(id=task_node.created_by) # if userobj and userobj not in user_to_be_notified: # user_to_be_notified.append(userobj) for each_author in task_node.author_set: each_author = User.objects.get(id=each_author) if each_author and each_author not in user_to_be_notified: user_to_be_notified.append(each_author) # Sending notification to all watchers about the updates of the task for eachuser in user_to_be_notified: activ="task updated" msg = "Task '" + task_node.name + \ "' has been updated by " + request.user.username + \ "\n - Changes: " + str(change_list).strip('[]') + \ "\n - Status: " + request.POST.get('Status','') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) bx=User.objects.get(username=eachuser) set_notif_val(request,group_id,msg,activ,bx) if change_list or content_org: GST_task_update_history = node_collection.one({'_type': "GSystemType", 'name': 'task_update_history'}) update_node = node_collection.collection.GSystem() get_node_common_fields(request, update_node, group_id, GST_task_update_history) if change_list: update_node.altnames = unicode(str(change_list)) else: update_node.altnames = unicode('[]') update_node.prior_node = [task_node._id] update_node.name = unicode(task_node.name+"-update_history") update_node.save(groupid=group_id) update_node.name = unicode(task_node.name+"-update_history-"+str(update_node._id)) update_node.save(groupid=group_id) task_node.post_node.append(update_node._id) task_node.save(groupid=group_id) # patch GST_TASK = node_collection.one({'_type': "GSystemType", 'name': 'Task'}) get_node_common_fields(request, task_node, group_id, GST_TASK) task_node.save(groupid=group_id)
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given person-type. """ auth = None if ObjectId.is_valid(group_id) is False : group_ins = node_collection.one({'_type': "Group", "name": group_id}) auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else : auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth : group_id = str(auth._id) else : pass app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" person_gst = None person_gs = None college_node = None college_id = None student_enrollment_code = u"" create_student_enrollment_code = False existing_colg = [] registration_date = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) college_node = node_collection.one({ "_id": ObjectId(group_id), "relation_set.group_of": {"$exists": True} }, { "relation_set.group_of": 1 }) if app_set_id: person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_create_edit.html" title = person_gst.name person_gs = node_collection.collection.GSystem() person_gs.member_of.append(person_gst._id) if app_set_instance_id: person_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(person_gs)#.property_order if request.method == "POST": if person_gst.name == "Student" and "_id" not in person_gs: create_student_enrollment_code = True # [A] Save person-node's base-field(s) is_changed = get_node_common_fields(request, person_gs, group_id, person_gst) if is_changed: # Remove this when publish button is setup on interface person_gs.status = u"PUBLISHED" person_gs.save(is_changed=is_changed,groupid=group_id) for each_rel in person_gs.relation_set: if each_rel and "officer_incharge_of" in each_rel: existing_colg = each_rel["officer_incharge_of"] if college_node: mis_admin = node_collection.one({ "_type": "Group", "name": "MIS_admin" }, { "_id": 1 } ) node_collection.collection.update({ "_id": person_gs._id }, { "$addToSet": {"group_set": mis_admin._id} }, upsert=False, multi=False ) # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one({'_id': field_set['_id']}) fi_name = field_instance["name"] field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used user_id = request.user.id if fi_name in request.FILES: field_value = request.FILES[fi_name] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = person_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes if fi_name in request.POST: field_value = request.POST[fi_name] # field_instance_type = "GAttribute" if fi_name in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif fi_name in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") registration_date = field_value else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: person_gs_triple_instance = create_gattribute(person_gs._id, node_collection.collection.AttributeType(field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get(fi_name, "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(fi_name) else: field_value_list = request.POST.getlist(fi_name) if META_TYPE[3] in field_instance.member_of_names_list: # If Binary relationship found # [id, id, ...] # field_instance_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value else: # Relationship Other than Binary one found; e.g, Triadic # [[id, id, ...], [id, id, ...], ...] # field_instance_type = "GRelation" for i, field_value_inner_list in enumerate(field_value_list): for j, field_value in enumerate(field_value_inner_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i][j] = field_value person_gs_triple_instance = create_grelation(person_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # Setting enrollment code for student node only while creating it if create_student_enrollment_code: # Create enrollment code for student node only while registering a new node for rel in college_node.relation_set: if rel and "group_of" in rel: college_id = rel["group_of"][0] student_enrollment_code = get_student_enrollment_code(college_id, person_gs._id, registration_date, ObjectId(group_id)) enrollment_code_at = node_collection.one({ "_type": "AttributeType", "name": "enrollment_code" }) try: ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code) except Exception as e: print "\n StudentEnrollmentCreateError: " + str(e) + "!!!" # [C] Code to link GSystem Node and Author node via "has_login" relationship; # and Subscribe the Author node to College group if user "Program Officer" person_gs.reload() auth_node = None for attr in person_gs.attribute_set: if "email_id" in attr: if attr["email_id"]: auth_node = node_collection.one({'_type': "Author", 'email': attr["email_id"].lower()}) break if auth_node: has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"}) if has_login_rt: # Linking GSystem Node and Author node via "has_login" relationship; gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id) # Set author_agency field's value of author node as "Program Officer" # Required to identify at time of log-in in order to display # required modules defined for Program Officers under MIS GApp if auth_node.agency_type != u"Program Officer": auth_node.agency_type = u"Program Officer" auth_node.save(groupid=group_id) if "Program Officer" in person_gs.member_of_names_list: # If Person node (GSystem) is of Program Officer type # then only go for subscription college_id_list = [] # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of") for rel in person_gs.relation_set: if "officer_incharge_of" in rel: if rel["officer_incharge_of"]: for college_id in rel["officer_incharge_of"]: if college_id not in college_id_list: college_id_list.append(college_id) break # break outer-loop (of relation_set) if college_id_list: # If College's ObjectId exists (list as PO might be assigned to more than one college) # Then prepare a list of their corresponding private group(s) (via "has_group") college_cur = node_collection.find( {'_id': {'$in': college_id_list}}, {'relation_set.has_group': 1} ) college_group_id_list = [] for college in college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][0] not in college_group_id_list: college_group_id_list.append(rel["has_group"][0]) break # break inner-loop (college.relation_set) if college_group_id_list: # If college-group list exists # Then update their group_admin field (append PO's created_by) res = node_collection.collection.update( {'_id': {'$in': college_group_id_list}}, {'$addToSet': {'group_admin': auth_node.created_by}}, upsert=False, multi=True ) old_college_id_list = [] if existing_colg: if len(existing_colg) > len(college_id_list): for each_colg_id in existing_colg: if each_colg_id not in college_id_list: old_college_id_list.append(each_colg_id) old_college_cur = node_collection.find( {'_id': {'$in': old_college_id_list}}, {'relation_set.has_group': 1} ) old_college_group_id_list = [] for college in old_college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][0] not in old_college_group_id_list: old_college_group_id_list.append(rel["has_group"][0]) break # break inner-loop (college.relation_set) if old_college_group_id_list: # If college-group list exists # Then update their group_admin field (remove PO's created_by) res = node_collection.collection.update( {'_id': {'$in': old_college_group_id_list}, '$or': [{'group_admin': auth_node.created_by}, {'author_set': auth_node.created_by}]}, {'$pull': {'group_admin': auth_node.created_by, 'author_set': auth_node.created_by}}, upsert=False, multi=True ) # The code below is commented as the college groups are PRIVATE. # for rel in person_gs.relation_set: # if rel and "officer_incharge_of" in rel: # pass # else: # node_collection.collection.update({'_id': auth_node._id}, # {'$set': {'agency_type': u"Other"}}, # upsert=False, multi=False # ) # Its purpose is to change the agency type back to Other auth_node.reload() # if person_gst.name != "Student": # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) # else: return HttpResponseRedirect(reverse('mis:mis_app_instance_detail',kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id, "app_set_instance_id":unicode(person_gs._id)})) # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) default_template = "ndf/person_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list } if person_gst and person_gst.name in ["Voluntary Teacher", "Master Trainer"]: nussd_course_type = node_collection.one({'_type': "AttributeType", 'name': "nussd_course_type"}, {'_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1}) if nussd_course_type["data_type"] == "IS()": # Below code does little formatting, for example: # data_type: "IS()" complex_value: [u"ab", u"cd"] dt: # "IS(u'ab', u'cd')" dt = "IS(" for v in nussd_course_type.complex_data_type: dt = dt + "u'" + v + "'" + ", " dt = dt[:(dt.rfind(", "))] + ")" nussd_course_type["data_type"] = dt nussd_course_type["data_type"] = eval(nussd_course_type["data_type"]) nussd_course_type["value"] = None context_variables['nussd_course_type'] = nussd_course_type if app_set_instance_id: person_gs.get_neighbourhood(person_gs.member_of) if "trainer_teaches_course_in_college" in person_gs: l = [] for each_course_college in person_gs.trainer_teaches_course_in_college: # Fetch Course Type (i.e. nussd_course_type) ct = "" for each_attr in each_course_college[0].attribute_set: if "nussd_course_type" in each_attr and each_attr: ct = each_attr["nussd_course_type"] break univ_name = "" for each_rel in each_course_college[1].relation_set: if "college_affiliated_to" in each_rel and each_rel: univ = node_collection.find_one({"_id": {"$in": each_rel["college_affiliated_to"]}}) univ_name = univ.name if univ else "" l.append(( ct, each_course_college[0].name, each_course_college[1].name, each_course_college[0]._id.__str__(), each_course_college[1]._id.__str__(), univ_name )) if l: person_gs.trainer_teaches_course_in_college = l context_variables['node'] = person_gs try: return render_to_response([template, default_template], context_variables, context_instance = RequestContext(request) ) except TemplateDoesNotExist as tde: error_message = "\n PersonCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def create_edit_quiz_item(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_object = node_collection.one({'_id': ObjectId(group_id)}) node = None quiz_node = None quiz_node_id = None quiz_item_node = None gst_quiz_item = node_collection.one({'_type': u'GSystemType', 'name': u'QuizItem'}) # if "CourseEventGroup" in group_object.member_of_names_list: # gst_quiz_item = node_collection.one({'_type': u'GSystemType', 'name': u'QuizItemEvent'}) # if node_id: # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) quiz_node_id = request.GET.get('quiznode','') return_url = request.GET.get('return_url','') context_variables = { 'title': gst_quiz_item.name, 'quiz_type_choices': QUIZ_TYPE_CHOICES, 'group_id': group_id, 'groupid': group_id, } if return_url: context_variables['return_url'] = return_url if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) context_variables['quiz_node_id'] = quiz_node._id if node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node else: # Edit a question quiz_item_node = node if request.method == "POST": usrid = int(request.user.id) usrname = unicode(request.user.username) # if node_id: # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # else: # # Add miscellaneous question # quiz_item_node = node_collection.collection.GSystem() if node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node quiz_item_node = node_collection.collection.GSystem() else: # Edit a question quiz_item_node = node else: # Add miscellaneous question quiz_item_node = node_collection.collection.GSystem() # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # question_content = request.POST.get('content_org','') question_content = request.POST.get('quiz_item_name','Untitled') question_content = question_content.split(' ') question_content = question_content[:4] question_content = ' '.join(question_content) # print "\n\n question_content---",question_content question_content = re.sub('<[^>]*>', ' ', question_content) quiz_item_node.name = unicode(question_content) quiz_type_AT = node_collection.one({'_type': "AttributeType", 'name': "quiz_type"}) options_AT = node_collection.one({'_type': "AttributeType", 'name': "options"}) correct_answer_AT = node_collection.one({'_type': "AttributeType", 'name': "correct_answer"}) quizitem_show_correct_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_show_correct_ans"}) quizitem_problem_weight_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_problem_weight"}) quizitem_max_attempts_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_max_attempts"}) quizitem_check_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_check_answer"}) quiz_node_id = request.POST.get('quiz_node_id','') maximum_attempts_val = request.POST.get('maximum_attempts','1') problem_weight_val = request.POST.get('problem_weight','1') show_correct_ans_val = request.POST.get('show_correct_ans','False') check_ans_val = request.POST.get('check_ans','False') # print "\n\n maximum_attempts",maximum_attempts_val # print "\n problem_weight",problem_weight_val # print "\n show_correct_ans",show_correct_ans_val quiz_item_node.save(is_changed=get_node_common_fields(request, quiz_item_node, group_id, gst_quiz_item),groupid=group_id) if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) quiz_type = request.POST.get('quiz_type_val','') # create gattribute quiz_type,options, correct_answer # quiz_item_node['quiz_type'] = unicode(quiz_type) create_gattribute(quiz_item_node._id, quizitem_max_attempts_AT, int(maximum_attempts_val)) create_gattribute(quiz_item_node._id, quizitem_problem_weight_AT, float(problem_weight_val)) create_gattribute(quiz_item_node._id, quizitem_show_correct_ans_AT, eval(show_correct_ans_val)) create_gattribute(quiz_item_node._id, quiz_type_AT, unicode(quiz_type)) create_gattribute(quiz_item_node._id, quizitem_check_ans_AT, eval(check_ans_val)) # If "quiz_type" is either 'Single-Choice' or 'Multiple-Choice', then only extract options options = [] if quiz_type != QUIZ_TYPE_CHOICES[0]: no_of_options = int(request.POST.get('no_of_options','')) # quiz_item_node['options'] = [] # print "\n\n no_of_options",no_of_options i = 1 while i <= no_of_options: options.append(request.POST.get("option" if i == 1 else "option_"+str(i))) i = i + 1 # quiz_item_node['options'] = options create_gattribute(quiz_item_node._id, options_AT, options) # Extracting correct-answer, depending upon 'Multiple-Choice' / 'Single-Choice' qt_initial = quiz_type[:quiz_type.find("-")].lower() # quiz_item_node['correct_answer'] = [] correct_ans_val = None if quiz_type == QUIZ_TYPE_CHOICES[1]: # Single Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'].append(correct_answer) elif quiz_type == QUIZ_TYPE_CHOICES[2]: # Multiple Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'] = correct_answer if correct_ans_val: # To handle if Quiz-type is Short-Response correct_answer = map(int,correct_ans_val) # Convert list of unicode ele to list of int ele correct_ans_val_list = [options[each_val-1] for each_val in correct_answer] create_gattribute(quiz_item_node._id, correct_answer_AT, correct_ans_val_list) # thread_obj = create_thread_for_node(request,group_id, quiz_item_node) quiz_item_node.reload() quiz_item_node.status = u"PUBLISHED" quiz_item_node.save(groupid=group_id) if "QuizItemEvent" in quiz_item_node.member_of_names_list: # Create thread node create_thread_for_node_flag = True if quiz_item_node.relation_set: for eachrel in quiz_item_node.relation_set: if eachrel and "has_thread" in eachrel: create_thread_for_node_flag = False if create_thread_for_node_flag: return_status = create_thread_for_node(request,group_id, quiz_item_node) print "\n\n return_status === ", return_status return_url = request.POST.get("return_url") # print "\n\n return_url", return_url, type(return_url) if return_url: if return_url == "groupchange": return HttpResponseRedirect(reverse('groupchange', kwargs={'group_id': group_id})) elif return_url == "course_content": return HttpResponseRedirect(reverse('course_content', kwargs={'group_id': group_id})) return HttpResponseRedirect(return_url) if quiz_node: quiz_node.collection_set.append(quiz_item_node._id) quiz_node.save(groupid=group_id) return HttpResponseRedirect(reverse('quiz', kwargs={'group_id': group_id})) else: if node_id: if quiz_item_node: quiz_item_node.get_neighbourhood(quiz_item_node.member_of) context_variables['node'] = quiz_item_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # context_variables['quiz_node']=quiz_node return render_to_response("ndf/quiz_item_create_edit.html", context_variables, context_instance=RequestContext(request) )
def theme_topic_create_edit(request, group_id, app_set_id=None): ##################### # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) ###################### nodes_dict = [] create_edit = True themes_hierarchy = False themes_list_items = "" themes_cards = "" title = "" node = "" theme_topic_node = "" drawers = None drawer = None app_id = None nodes_list = [] parent_nodes_collection = "" translate=request.GET.get('translate','') app_GST = node_collection.find_one({"_id":ObjectId(app_set_id)}) if app_GST._id != theme_GST._id: app_obj = node_collection.one({'_id': ObjectId(app_GST.member_of[0])}) else: app_obj = theme_GST if app_obj: app_id = app_obj._id shelves = [] shelf_list = {} auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth: has_shelf_RT = node_collection.one({'_type': 'RelationType', 'name': u'has_shelf' }) shelf = triple_collection.find({'_type': 'GRelation', 'subject': ObjectId(auth._id), 'relation_type.$id': has_shelf_RT._id}) shelf_list = {} if shelf: for each in shelf: shelf_name = node_collection.one({'_id': ObjectId(each.right_subject)}) shelves.append(shelf_name) shelf_list[shelf_name.name] = [] for ID in shelf_name.collection_set: shelf_item = node_collection.one({'_id': ObjectId(ID) }) shelf_list[shelf_name.name].append(shelf_item.name) else: shelves = [] if request.method == "POST": if app_GST: create_edit = True themes_list_items = "" root_themes = [] root_themes_id = [] nodes_list = [] name = request.POST.get('name') collection_list = request.POST.get('collection_list','') prior_node_list = request.POST.get('prior_node_list','') teaches_list = request.POST.get('teaches_list','') assesses_list = request.POST.get('assesses_list','') # To find the root nodes to maintain the uniquness while creating and editing themes nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes_id.append(each._id) if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == "true": # For creating new themes & Topics themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True if name or translate == "true": if not name.upper() in (theme_name.upper() for theme_name in root_themes) or translate == "true": if translate != "true": theme_topic_node = node_collection.collection.GSystem() # get_node_common_fields(request, theme_topic_node, group_id, app_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, app_GST),groupid=group_id) if translate == "true": global list_trans_coll list_trans_coll = [] coll_set1=get_coll_set(app_GST._id) for each in coll_set1: theme_topic_node = node_collection.collection.GSystem() if "Theme" in each.member_of_names_list: app_obj = theme_GST if "theme_item" in each.member_of_names_list: app_obj = theme_item_GST if "topic" in each.member_of_names_list: app_obj = topic_GST theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, app_obj, each),groupid=group_id) coll_set_dict[each._id]=theme_topic_node._id relation_type = node_collection.one({'_type':'RelationType', 'name':'translation_of'}) # grelation=collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=each._id # grelation.right_subject=theme_topic_node._id # grelation.name=u"" # grelation.save() gr_node = create_grelation(each._id, relation_type, theme_topic_node._id) for each in coll_set1: #if "Theme" in each.member_of_names_list: if each.collection_set: for collset in each.collection_set: p=coll_set_dict[each._id] parent_node = node_collection.one({'_id':ObjectId(str(p))}) n= coll_set_dict[collset] sub_node = node_collection.one({'_id':ObjectId(str(n))}) parent_node.collection_set.append(sub_node._id) parent_node.save(groupid=group_id) # To return themes card view for listing theme nodes after creating new Themes nodes.rewind() nodes_dict = nodes else: themes_list_items = False create_edit = False themes_hierarchy = True theme_topic_node = node_collection.one({'_id': ObjectId(app_GST._id)}) # For edititng themes if theme_GST._id in app_GST.member_of and translate != "true": # To find themes uniqueness within the context of its parent Theme collection, while editing theme name root_themes = [] nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: root_themes.append(each.name) if name: if name.upper() != theme_topic_node.name.upper(): if not name.upper() in (theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_GST),groupid=group_id) else: theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_GST),groupid=group_id) if translate != "true": # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) # End of storing collection title = theme_GST.name nodes.rewind() nodes_dict = nodes # This will return to Themes Hierarchy themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True elif theme_item_GST._id in app_GST.member_of and translate != "true": title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) # Code for fetching drawer2 for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k) }) dict2.append(obj) dict_drawer['2'] = dict2 # drawers = dict_drawer # End of code for drawer2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme item nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) if not prior_theme_collection: root_nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for k in root_nodes: if app_GST._id in k.collection_set: root_themes = [] root_themes_id = [] for l in k.collection_set: objs = node_collection.one({'_id': ObjectId(l)}) root_themes.append(objs.name) root_themes_id.append(objs._id) # End of finding unique theme names for editing name # For adding a sub-theme-items and maintianing their uniqueness within their context nodes_list = [] for each in app_GST.collection_set: sub_theme = node_collection.one({'_id': ObjectId(each) }) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes if name: if name.upper() != theme_topic_node.name.upper(): # If "Name" has changed if theme_topic_node._id in root_themes_id: # If editing node in root theme items if not name.upper() in (theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) else: # If editing theme item in prior_theme_collection hierarchy if not name.upper() in (theme_name.upper() for theme_name in prior_theme_collection): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) else: # If name not changed but other fields has changed theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) if translate != "true" and collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) # End of storing collection # This will return to Themes items edit if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False # For editing topics elif topic_GST._id in app_GST.member_of: root_topics = [] nodes_list = [] # To find the root nodes to maintain the uniquness while creating and editing topics nodes = node_collection.find({'member_of': {'$all': [topic_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_topics.append(each.name) # End of finding the root nodes if name: if theme_topic_node.name != name: topic_name = theme_topic_node.name if not name.upper() in (theme_name.upper() for theme_name in root_topics): theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) elif topic_name.upper() == name.upper(): theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) else: theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) if collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) title = topic_GST.name # To fill the metadata info while creating and editing topic node metadata = request.POST.get("metadata_info", '') if metadata: # Only while metadata editing if metadata == "metadata": if theme_topic_node: get_node_metadata(request,theme_topic_node) # End of filling metadata if prior_node_list != '': theme_topic_node.prior_node = [] prior_node_list = prior_node_list.split(",") i = 0 while (i < len(prior_node_list)): node_id = ObjectId(prior_node_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.prior_node.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) if teaches_list !='': teaches_list=teaches_list.split(",") create_grelation_list(theme_topic_node._id,"teaches",teaches_list) if assesses_list !='': assesses_list=assesses_list.split(",") create_grelation_list(theme_topic_node._id,"assesses",assesses_list) # This will return to edit topic if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False else: app_node = None nodes_list = [] app_GST = node_collection.find_one({"_id":ObjectId(app_set_id)}) # print "\napp_GST in else: ",app_GST.name,"\n" if app_GST: # For adding new Theme & Topic if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == True: print "22222" title = app_GST.name node = "" root_themes = [] # To find the root nodes to maintain the uniquness while creating new themes nodes = node_collection.find({'member_of': {'$all': [app_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes = json.dumps(root_themes) nodes_list = root_themes # End of finding unique root level Themes else: if theme_GST._id in app_GST.member_of: title = "Theme" node = app_GST prior_theme_collection = [] parent_nodes_collection = "" drawer = [] # End of editing Themes # For editing theme item if theme_item_GST._id in app_GST.member_of: title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k) }) dict2.append(obj) dict_drawer['2'] = dict2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme name nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) # End of finding unique theme names for editing name # For adding a sub-themes and maintianing their uniqueness within their context for each in app_GST.collection_set: sub_theme = node_collection.one({'_id': ObjectId(each) }) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes # for editing topic elif topic_GST._id in app_GST.member_of: title = topic_GST.name node = app_GST prior_theme_collection = [] parent_nodes_collection = "" node.get_neighbourhood(node.member_of) # To find topics uniqueness within the context of its parent Theme item collection, while editing topic name nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) # End of finding unique theme names for editing name if translate: global list_trans_coll list_trans_coll = [] trans_coll_list = get_coll_set(str(app_GST._id)) print LANGUAGES return render_to_response("ndf/translation_page.html", {'group_id': group_id,'groupid': group_id,'title': title, 'node': app_GST, 'lan':LANGUAGES, 'list1':trans_coll_list },context_instance = RequestContext(request) ) if title == "Topic": return render_to_response("ndf/node_edit_base.html", {'group_id': group_id,'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'shelf_list': shelf_list,'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy,'app_id': app_id,'appId':app._id, 'nodes_list': nodes_list,'title': title,'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id,'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items,'nodes':nodes_dict,'lan':LANGUAGES },context_instance = RequestContext(request) ) return render_to_response("ndf/theme.html", {'group_id': group_id,'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'theme_GST':theme_GST, 'theme_GST':theme_GST, 'shelf_list': shelf_list,'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy,'app_id': app_id,'appId':app._id, 'nodes_list': nodes_list,'title': title,'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id,'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items,'nodes':nodes_dict,'lan':LANGUAGES },context_instance = RequestContext(request) )
def create_edit_quiz_item(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_object = node_collection.one({'_id': ObjectId(group_id)}) node = None quiz_node = None quiz_node_id = None quiz_item_node = None gst_quiz_item = node_collection.one({ '_type': u'GSystemType', 'name': u'QuizItem' }) # if "CourseEventGroup" in group_object.member_of_names_list: # gst_quiz_item = node_collection.one({'_type': u'GSystemType', 'name': u'QuizItemEvent'}) # if node_id: # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) quiz_node_id = request.GET.get('quiznode', '') return_url = request.GET.get('return_url', '') context_variables = { 'title': gst_quiz_item.name, 'quiz_type_choices': QUIZ_TYPE_CHOICES, 'group_id': group_id, 'groupid': group_id, } if return_url: context_variables['return_url'] = return_url if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) context_variables['quiz_node_id'] = quiz_node._id if node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node else: # Edit a question quiz_item_node = node if request.method == "POST": usrid = int(request.user.id) usrname = unicode(request.user.username) # if node_id: # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # else: # # Add miscellaneous question # quiz_item_node = node_collection.collection.GSystem() if node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node quiz_item_node = node_collection.collection.GSystem() else: # Edit a question quiz_item_node = node else: # Add miscellaneous question quiz_item_node = node_collection.collection.GSystem() # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # question_content = request.POST.get('content_org','') question_content = request.POST.get('quiz_item_name', 'Untitled') question_content = question_content.split(' ') question_content = question_content[:4] question_content = ' '.join(question_content) # print "\n\n question_content---",question_content question_content = re.sub('<[^>]*>', ' ', question_content) quiz_item_node.name = unicode(question_content) quiz_type_AT = node_collection.one({ '_type': "AttributeType", 'name': "quiz_type" }) options_AT = node_collection.one({ '_type': "AttributeType", 'name': "options" }) correct_answer_AT = node_collection.one({ '_type': "AttributeType", 'name': "correct_answer" }) quizitem_show_correct_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitem_show_correct_ans" }) quizitem_problem_weight_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitem_problem_weight" }) quizitem_max_attempts_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitem_max_attempts" }) quizitem_check_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitem_check_answer" }) quiz_node_id = request.POST.get('quiz_node_id', '') maximum_attempts_val = request.POST.get('maximum_attempts', '1') problem_weight_val = request.POST.get('problem_weight', '1') show_correct_ans_val = request.POST.get('show_correct_ans', 'False') check_ans_val = request.POST.get('check_ans', 'False') # print "\n\n maximum_attempts",maximum_attempts_val # print "\n problem_weight",problem_weight_val # print "\n show_correct_ans",show_correct_ans_val quiz_item_node.save(is_changed=get_node_common_fields( request, quiz_item_node, group_id, gst_quiz_item), groupid=group_id) if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) quiz_type = request.POST.get('quiz_type_val', '') # create gattribute quiz_type,options, correct_answer # quiz_item_node['quiz_type'] = unicode(quiz_type) create_gattribute(quiz_item_node._id, quizitem_max_attempts_AT, int(maximum_attempts_val)) create_gattribute(quiz_item_node._id, quizitem_problem_weight_AT, float(problem_weight_val)) create_gattribute(quiz_item_node._id, quizitem_show_correct_ans_AT, eval(show_correct_ans_val)) create_gattribute(quiz_item_node._id, quiz_type_AT, unicode(quiz_type)) create_gattribute(quiz_item_node._id, quizitem_check_ans_AT, eval(check_ans_val)) # If "quiz_type" is either 'Single-Choice' or 'Multiple-Choice', then only extract options options = [] if quiz_type != QUIZ_TYPE_CHOICES[0]: no_of_options = int(request.POST.get('no_of_options', '')) # quiz_item_node['options'] = [] # print "\n\n no_of_options",no_of_options i = 1 while i <= no_of_options: options.append( request.POST.get("option" if i == 1 else "option_" + str(i))) i = i + 1 # quiz_item_node['options'] = options create_gattribute(quiz_item_node._id, options_AT, options) # Extracting correct-answer, depending upon 'Multiple-Choice' / 'Single-Choice' qt_initial = quiz_type[:quiz_type.find("-")].lower() # quiz_item_node['correct_answer'] = [] correct_ans_val = None if quiz_type == QUIZ_TYPE_CHOICES[1]: # Single Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'].append(correct_answer) elif quiz_type == QUIZ_TYPE_CHOICES[2]: # Multiple Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'] = correct_answer if correct_ans_val: # To handle if Quiz-type is Short-Response correct_answer = map( int, correct_ans_val ) # Convert list of unicode ele to list of int ele correct_ans_val_list = [ options[each_val - 1] for each_val in correct_answer ] create_gattribute(quiz_item_node._id, correct_answer_AT, correct_ans_val_list) # thread_obj = create_thread_for_node(request,group_id, quiz_item_node) quiz_item_node.reload() quiz_item_node.status = u"PUBLISHED" quiz_item_node.save(groupid=group_id) if "QuizItemEvent" in quiz_item_node.member_of_names_list: # Create thread node create_thread_for_node_flag = True if quiz_item_node.relation_set: for eachrel in quiz_item_node.relation_set: if eachrel and "has_thread" in eachrel: create_thread_for_node_flag = False if create_thread_for_node_flag: return_status = create_thread_for_node(request, group_id, quiz_item_node) print "\n\n return_status === ", return_status return_url = request.POST.get("return_url") # print "\n\n return_url", return_url, type(return_url) if return_url: if return_url == "groupchange": return HttpResponseRedirect( reverse('groupchange', kwargs={'group_id': group_id})) elif return_url == "course_content": return HttpResponseRedirect( reverse('course_content', kwargs={'group_id': group_id})) return HttpResponseRedirect(return_url) if quiz_node: quiz_node.collection_set.append(quiz_item_node._id) quiz_node.save(groupid=group_id) return HttpResponseRedirect( reverse('quiz', kwargs={'group_id': group_id})) else: if node_id: if quiz_item_node: quiz_item_node.get_neighbourhood(quiz_item_node.member_of) context_variables['node'] = quiz_item_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # context_variables['quiz_node']=quiz_node return render_to_response("ndf/quiz_item_create_edit.html", context_variables, context_instance=RequestContext(request))
def data_review_save(request, group_id): ''' Method to save each and every data-row edit of data review app ''' userid = request.user.pk try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_obj = node_collection.one({"_id": ObjectId(group_id)}) node_oid = request.POST.get("node_oid", "") node_details = request.POST.get("node_details", "") node_details = json.loads(node_details) # print "node_details : ", node_details # updating some key names of dictionary as per get_node_common_fields. node_details["lan"] = node_details.pop("language") node_details["prior_node_list"] = node_details.pop("prior_node") node_details["login-mode"] = node_details.pop("access_policy") status = node_details.pop("status") # node_details["collection_list"] = node_details.pop("collection") for future use # Making copy of POST QueryDict instance. # To make it mutable and fill in node_details value/s. post_req = request.POST.copy() # removing node_details dict from req post_req.pop('node_details') # adding values to post req post_req.update(node_details) # overwriting request.POST with newly created QueryDict instance post_req request.POST = post_req # print "\n---\n", request.POST, "\n---\n" license = request.POST.get('license', '') file_node = node_collection.one({"_id": ObjectId(node_oid)}) if request.method == "POST": edit_summary = [] file_node_before = file_node.copy( ) # copying before it is getting modified is_changed = get_node_common_fields(request, file_node, group_id, GST_FILE) for key, val in file_node_before.iteritems(): if file_node_before[key] != file_node[key]: temp_edit_summ = {} temp_edit_summ["name"] = "Field: " + key temp_edit_summ["before"] = file_node_before[key] temp_edit_summ["after"] = file_node[key] edit_summary.append(temp_edit_summ) # to fill/update attributes of the node and get updated attrs as return ga_nodes = get_node_metadata(request, file_node, is_changed=True) if len(ga_nodes): is_changed = True # adding the edit attribute name in summary for each_ga in ga_nodes: temp_edit_summ = {} temp_edit_summ["name"] = "Attribute: " + each_ga["node"][ "attribute_type"]["name"] temp_edit_summ["before"] = each_ga["before_obj_value"] temp_edit_summ["after"] = each_ga["node"]["object_value"] edit_summary.append(temp_edit_summ) teaches_list = request.POST.get('teaches', '') # get the teaches list prev_teaches_list = request.POST.get( "teaches_prev", "") # get the before-edit teaches list # check if teaches list exist means nodes added/removed for teaches relation_type # also check for if previous teaches list made empty with prev_teaches_list if (teaches_list != '') or prev_teaches_list: teaches_list = teaches_list.split(",") if teaches_list else [] teaches_list = [ObjectId(each_oid) for each_oid in teaches_list] relation_type_node = node_collection.one({ '_type': "RelationType", 'name': 'teaches' }) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes ] if gr_nodes else [] prev_teaches_list = prev_teaches_list.split( ",") if prev_teaches_list else [] prev_teaches_list = [ ObjectId(each_oid) for each_oid in prev_teaches_list ] if len(gr_nodes_oid_list) == len(prev_teaches_list) and set( gr_nodes_oid_list) == set(prev_teaches_list): pass else: rel_nodes = triple_collection.find({ '_type': "GRelation", 'subject': file_node._id, 'relation_type': relation_type_node._id }) rel_oid_name = {} for each in rel_nodes: temp = {} temp[each.right_subject] = each.name rel_oid_name.update(temp) is_changed = True temp_edit_summ = {} temp_edit_summ["name"] = "Relation: Teaches" temp_edit_summ["before"] = [ rel_oid_name[each_oid].split(" -- ")[2] for each_oid in prev_teaches_list ] temp_edit_summ["after"] = [ rel_oid_name[each_oid].split(" -- ")[2] for each_oid in gr_nodes_oid_list ] edit_summary.append(temp_edit_summ) assesses_list = request.POST.get('assesses_list', '') if assesses_list != '': assesses_list = assesses_list.split(",") assesses_list = [ObjectId(each_oid) for each_oid in assesses_list] relation_type_node = node_collection.one({ '_type': "RelationType", 'name': 'assesses' }) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes ] if len(gr_nodes_oid_list) == len(teaches_list) and set( gr_nodes_oid_list) == set(teaches_list): pass else: is_changed = True # changing status to draft even if attributes/relations are changed if is_changed: file_node.status = unicode("DRAFT") file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) # checking if user is authenticated to change the status of node if status and ((group_obj.is_gstaff(request.user)) or (userid in group_obj.author_set)): if file_node.status != status: file_node.status = unicode(status) file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) is_changed = True if is_changed: file_node.save(groupid=group_id) # print edit_summary return HttpResponse(file_node.status)
def create_edit_page(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass group_name, group_id = get_group_name_id(group_id) ce_id = request.GET.get('course_event_id','') blog_type = request.GET.get('blog_type','') res = request.GET.get('res','') program_res = request.GET.get('program_res','') context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id, 'ce_id': ce_id, 'res':res, 'program_res':program_res, 'blog_type': blog_type } group_obj = node_collection.one({'_id': ObjectId(group_id)}) available_nodes = node_collection.find({'_type': u'GSystem', 'member_of': ObjectId(gst_page._id),'group_set': ObjectId(group_id), '_id': {'$ne': ObjectId(node_id)} }) nodes_list = [] thread = None url_name = "/home" # for each in available_nodes: # nodes_list.append(str((each.name).strip().lower())) # loop replaced by a list comprehension node_list = [str((each.name).strip().lower()) for each in available_nodes] # print "available_nodes: ", node_list if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) page_name = request.POST.get('name', '') # print "====== page_name: ", page_name if page_name.strip().lower() in node_list and not node_id: new_page=False return render_to_response("error_base.html", {'message': 'Page with same name already exists in the group!'}, context_instance=RequestContext(request)) elif node_id: new_page = False page_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: new_page = True page_node = node_collection.collection.GSystem() # page_type = request.POST.getlist("type_of",'') ce_id = request.POST.get("ce_id",'') blog_type = request.POST.get('blog_type','') res = request.POST.get("res",'') program_res = request.POST.get('program_res','') # we are fetching the value of release_response flag # if this is set, it means, we can proceed to create a thread node # for the current page node. thread_create_val = request.POST.get("thread_create",'') # print "\n\n thread_create_val", thread_create_val # print "\n\n request.POST === ",request.POST # raise Exception("demo") # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) # print "\n\n help_info_page === ",help_info_page #program_res and res are boolean values if program_res: program_res = eval(program_res) if res: res = eval(res) if blog_type: blog_type = eval(blog_type) # if page_type: # objid= page_type[0] # if not ObjectId(objid) in page_node.type_of: # page_type1=[] # page_type1.append(ObjectId(objid)) # page_node.type_of = page_type1 # page_node.type_of page_node.save(is_changed=get_node_common_fields(request, page_node, group_id, gst_page)) # if course event grp's id is passed, it means # its a blog page added in notebook and hence set type_of field as "Blog page" # print "\n\n blog_type---",blog_type if blog_type: blogpage_gst = node_collection.one({'_type': "GSystemType", 'name': "Blog page"}) page_node.type_of = [blogpage_gst._id] elif GSTUDIO_SITE_NAME == "NROER" and "Author" in group_obj.member_of_names_list: infopage_gst = node_collection.one({'_type': "GSystemType", 'name': "Info page"}) page_node.type_of = [infopage_gst._id] # if the page created is as a resource in course or program event, # set status to PUBLISHED by default # one major reason for this, ONLY published nodes can be replicated. if res or program_res or ce_id: page_node.status = u"PUBLISHED" page_node.save() # if page is created in program event, add page_node to group's collection set if program_res: group_obj = node_collection.one({'_id': ObjectId(group_id)}) group_obj.collection_set.append(page_node._id) group_obj.save() discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"}) if thread_create_val == "Yes" or blog_type: create_gattribute(page_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request,group_id, page_node) else: create_gattribute(page_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if "None" not in help_info_page: has_help_rt = node_collection.one({'_type': "RelationType", 'name': "has_help"}) try: help_info_page = map(ObjectId, help_info_page) create_grelation(page_node._id, has_help_rt,help_info_page) page_node.reload() except Exception as invalidobjectid: # print invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(page_node._id,"has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id","") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=page_node._id, node_id=each_grel_id, deletion_type=0 ) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg # To fill the metadata info while creating and editing page node metadata = request.POST.get("metadata_info", '') if "CourseEventGroup" in group_obj.member_of_names_list and blog_type: if new_page: # counter_obj = Counter.get_counter_obj(request.user.id,ObjectId(group_id)) # # counter_obj.no_notes_written=counter_obj.no_notes_written+1 # counter_obj['page']['blog']['created'] += 1 # # counter_obj.course_score += GSTUDIO_NOTE_CREATE_POINTS # counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS # counter_obj.last_update = datetime.datetime.now() # counter_obj.save() active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur(active_user_ids_list, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['page']['blog']['created'] += 1 each_counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save() return HttpResponseRedirect(reverse('course_notebook_tab_note', kwargs={ 'group_id': group_id, 'tab': 'my-notes', 'notebook_id': page_node._id }) ) if ce_id or res or program_res: url_name = "/" + group_name + "/" + str(page_node._id) if ce_id: # url_name = "/" + group_name + "/#journal-tab" url_name = "/" + group_name if res or program_res: url_name = "/" + group_name + "/?selected=" + str(page_node._id) + "#view_page" # print "\n\n url_name---",url_name return HttpResponseRedirect(url_name) if metadata: # Only while metadata editing if metadata == "metadata": if page_node: get_node_metadata(request,page_node,is_changed=True) # End of filling metadata return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) else: if node_id: page_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) #page_node,ver=get_page(request,page_node) page_node.get_neighbourhood(page_node.member_of) context_variables['node'] = page_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # fetch Page instances # Page_node = node_collection.find_one({'_type':"GSystemType","name":"Page"}) page_instances = node_collection.find({"type_of": gst_page._id}) page_ins_list = [i for i in page_instances] context_variables['page_instance'] = page_ins_list context_variables['nodes_list'] = json.dumps(nodes_list) # print "\n\n context_variables----\n",context_variables return render_to_response("ndf/page_create_edit.html", context_variables, context_instance=RequestContext(request) )
def update(request, rt_list, at_list, task_node, group_id, group_name): file_id = (request.POST.get("files")) file_name = (request.POST.get("files_name")) user_to_be_notified = [] assignee_list = [] change_list = [] for each in rt_list: rel_type_node = node_collection.one({ '_type': "RelationType", 'name': each }) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value old_value = [] for rel in task_node.relation_set: for k in rel: if rel_type_node.name == k: vals_cur = node_collection.find({'_id': { '$in': rel[k] }}, {'name': 1}) for v_node in vals_cur: old_value.append(v_node.name) break new_value = [] vals_cur = node_collection.find({'_id': { '$in': field_value_list }}, {'name': 1}) for v_node in vals_cur: new_value.append(v_node.name) break if old_value != new_value: change_list.append( each.encode('utf8') + ' changed from ' + ", ".join(old_value) + ' to ' + ", ".join(new_value)) # updated details task_gs_triple_instance = create_grelation( task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) task_node.reload() for each in at_list: if request.POST.get(each, ""): attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': each }) attr = triple_collection.find_one({ "_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id }) if each == "Assignee": field_value = request.POST.getlist(each, "") for i, val in enumerate(field_value): field_value[i] = int(val) assignee_list_id = field_value for eachuser in assignee_list_id: bx = User.objects.get(id=int(eachuser)) if bx: if bx.username not in assignee_list: assignee_list.append(bx.username) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data( eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) if attr: # already attribute exist if not attr.object_value == field_value: # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details if attributetype_key["data_type"] == "datetime.datetime": change_list.append( each.encode('utf8') + ' changed from ' + attr.object_value.strftime("%d/%m/%Y") + ' to ' + field_value.strftime("%d/%m/%Y") ) # updated details else: change_list.append( each.encode('utf8') + ' changed from ' + str(attr.object_value) + ' to ' + str(field_value)) # updated details attr.object_value = field_value attr.save(groupid=group_id) else: # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each}) # newattribute = triple_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = request.POST.get(each,"") # newattribute.object_value = field_value # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, field_value) # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details change_list.append( each.encode('utf8') + ' set to ' + str(field_value)) # updated details elif each == 'Upload_Task': attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': 'Upload_Task' }) attr = triple_collection.find_one({ "_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id }) if attr: value = get_file_node(attr.object_value) change_list.append( each.encode('utf8') + ' changed from ' + str(value).strip('[]') + ' to ' + str(file_name)) # attr.object_value=file_id # attr.save() ga_node = create_gattribute(attr.subject, attributetype_key, file_id) else: # newattribute = node_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = file_id # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, file_id) change_list.append( each.encode('utf8') + ' set to ' + file_name.encode('utf8')) # updated details # userobj = User.objects.get(id=task_node.created_by) # if userobj and userobj not in user_to_be_notified: # user_to_be_notified.append(userobj) for each_author in task_node.author_set: each_author = User.objects.get(id=each_author) if each_author and each_author not in user_to_be_notified: user_to_be_notified.append(each_author) # Sending notification to all watchers about the updates of the task for eachuser in user_to_be_notified: activ = "task updated" msg = "Task '" + task_node.name + \ "' has been updated by " + request.user.username + \ "\n - Changes: " + str(change_list).strip('[]') + \ "\n - Status: " + request.POST.get('Status','') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) bx = User.objects.get(username=eachuser) set_notif_val(request, group_id, msg, activ, bx) if change_list or content_org: GST_task_update_history = node_collection.one({ '_type': "GSystemType", 'name': 'task_update_history' }) update_node = node_collection.collection.GSystem() get_node_common_fields(request, update_node, group_id, GST_task_update_history) if change_list: update_node.altnames = unicode(str(change_list)) else: update_node.altnames = unicode('[]') update_node.prior_node = [task_node._id] update_node.name = unicode(task_node.name + "-update_history") update_node.save(groupid=group_id) update_node.name = unicode(task_node.name + "-update_history-" + str(update_node._id)) update_node.save(groupid=group_id) task_node.post_node.append(update_node._id) task_node.save(groupid=group_id) # patch GST_TASK = node_collection.one({ '_type': "GSystemType", 'name': 'Task' }) get_node_common_fields(request, task_node, group_id, GST_TASK) task_node.save(groupid=group_id)
def organization_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given organization-type. """ auth = None # if ObjectId.is_valid(group_id) is False : # group_ins = node_collection.one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass group_name, group_id = get_group_name_id(group_id) app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)},{'_id':1, 'name':1}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" organization_gst = None organization_gs = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) if app_set_id: organization_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) template = "ndf/organization_create_edit.html" title = organization_gst.name organization_gs = node_collection.collection.GSystem() organization_gs.member_of.append(organization_gst._id) if app_set_instance_id: organization_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(organization_gs)#.property_order if request.method == "POST": # [A] Save organization-node's base-field(s) is_changed = get_node_common_fields(request, organization_gs, group_id, organization_gst) if is_changed: # Remove this when publish button is setup on interface organization_gs.status = u"PUBLISHED" organization_gs.save(is_changed=is_changed,groupid=group_id) # [B] Store AT and/or RT field(s) of given organization-node (i.e., organization_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one({'_id': field_set['_id']}) field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = organization_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: organization_gs_triple_instance = create_gattribute(organization_gs._id, node_collection.collection.AttributeType(field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get(field_instance["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(field_instance["name"]) else: field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value organization_gs_triple_instance = create_grelation(organization_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # [C] Create private group only for College GSystems if "College" in organization_gs.member_of_names_list: # Create a group for respective college node college_group, college_group_gr = create_college_group_and_setup_data(organization_gs) return HttpResponseRedirect( reverse( app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id} ) ) # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list } if app_set_instance_id: # organization_gs.get_neighbourhood(organization_gs.member_of) # context_variables['node'] = organization_gs context_variables['node_id'] = organization_gs._id context_variables['node_name'] = organization_gs.name try: return render_to_response(template, context_variables, context_instance = RequestContext(request) ) except TemplateDoesNotExist as tde: error_message = "\n OrganizationCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n OrganizationCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def create_edit_quiz_item(request, group_id, node_id=None, trans_node_id=None, lang='en'): """Creates/Modifies details about the given quiz-item. """ try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_object = node_collection.one({'_id': ObjectId(group_id)}) rt_translation_of = Node.get_name_id_from_type('translation_of', 'RelationType', get_obj=True) node = quiz_node = quiz_node_id = quiz_item_node = None existing_grel = translate_grel = None translated_node = Node.get_node_by_id(ObjectId(trans_node_id)) question_content = None options_list = [] group_object_member_of_names_list = group_object.member_of_names_list gst_quiz_item_node = node_collection.one({'_type': u'GSystemType', 'name': u'QuizItem'}) if "CourseEventGroup" in group_object_member_of_names_list or "announced_unit" in group_object_member_of_names_list: gst_quiz_item_node = gst_quiz_item_event current_url = resolve(request.path_info).url_name context_variables = { 'title': gst_quiz_item_node.name, 'quiz_type_choices': QUIZ_TYPE_CHOICES, 'group_id': group_id, 'groupid': group_id, } if "translate" in current_url: context_variables.update({'translate': True}) language = get_language_tuple(lang) quiz_node_id = request.GET.get('quiznode','') return_url = request.GET.get('return_url','') if return_url: context_variables['return_url'] = return_url if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) context_variables['quiz_node_id'] = quiz_node._id if node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node else: # Edit a question quiz_item_node = node if translated_node: question_content = translated_node.content options_list = get_quiz_item_options(translated_node) else: if quiz_item_node: question_content = quiz_item_node.content options_list = get_quiz_item_options(quiz_item_node) existing_grel = triple_collection.one({ '_type': 'GRelation', 'subject': ObjectId(quiz_item_node._id), 'relation_type': rt_translation_of._id, 'language': language }) if existing_grel: # get existing translated_node translated_node = Node.get_node_by_id(existing_grel.right_subject) if translated_node: trans_node_id = translated_node._id if request.method == "POST": usrid = int(request.user.id) usrname = unicode(request.user.username) translate = request.POST.get('translate', False) quiz_node_id = request.POST.get('quiz_node_id','') maximum_attempts_val = request.POST.get('maximum_attempts','1') problem_weight_val = request.POST.get('problem_weight','1') show_correct_ans_val = request.POST.get('show_correct_ans','False') check_ans_val = request.POST.get('check_ans','False') quiz_type = request.POST.get('quiz_type_val','') # print "\n\n maximum_attempts",maximum_attempts_val # print "\n problem_weight",problem_weight_val # print "\n show_correct_ans",show_correct_ans_val if translate: translated_node = created_trans_node(request, group_id, node_id, trans_node_id, language) if quiz_type == QUIZ_TYPE_CHOICES[1] or quiz_type == QUIZ_TYPE_CHOICES[2]: options = options_attachment(request, translated_node, language) # if node_id: # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # else: # # Add miscellaneous question # quiz_item_node = node_collection.collection.GSystem() elif node_id: node = node_collection.one({'_id': ObjectId(node_id)}) if gst_quiz._id in node.member_of: # Add question from a given Quiz category's context quiz_node = node quiz_item_node = node_collection.collection.GSystem() else: # Edit a question quiz_item_node = node else: # Add miscellaneous question quiz_item_node = node_collection.collection.GSystem() # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)}) # question_content = request.POST.get('content_org','') if not translate: name,content = get_quiz_item_name_content(request) quiz_item_node.name = unicode(name) quiz_type_AT = node_collection.one({'_type': "AttributeType", 'name': "quiz_type"}) correct_answer_AT = node_collection.one({'_type': "AttributeType", 'name': "correct_answer"}) quizitem_show_correct_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_show_correct_ans"}) quizitem_problem_weight_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_problem_weight"}) quizitem_max_attempts_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_max_attempts"}) quizitem_check_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_check_answer"}) quiz_item_node.altnames = quiz_item_node.content quiz_item_node.save(is_changed=get_node_common_fields(request, quiz_item_node, group_id, gst_quiz_item_node),groupid=group_id) # quiz_item_node.language = language if quiz_node_id: quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)}) # create gattribute quiz_type,options, correct_answer # quiz_item_node['quiz_type'] = unicode(quiz_type) create_gattribute(quiz_item_node._id, quizitem_max_attempts_AT, int(maximum_attempts_val)) create_gattribute(quiz_item_node._id, quizitem_problem_weight_AT, float(problem_weight_val)) create_gattribute(quiz_item_node._id, quizitem_show_correct_ans_AT, eval(show_correct_ans_val)) create_gattribute(quiz_item_node._id, quiz_type_AT, unicode(quiz_type)) create_gattribute(quiz_item_node._id, quizitem_check_ans_AT, eval(check_ans_val)) # If "quiz_type" is either 'Single-Choice' or 'Multiple-Choice', then only extract options if quiz_type == QUIZ_TYPE_CHOICES[1] or quiz_type == QUIZ_TYPE_CHOICES[2]: options = options_attachment(request, quiz_item_node, language) # Extracting correct-answer, depending upon 'Multiple-Choice' / 'Single-Choice' qt_initial = quiz_type[:quiz_type.find("-")].lower() # quiz_item_node['correct_answer'] = [] correct_ans_val = None if quiz_type == QUIZ_TYPE_CHOICES[1]: # Single Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'].append(correct_answer) elif quiz_type == QUIZ_TYPE_CHOICES[2]: # Multiple Choice correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial) # quiz_item_node['correct_answer'] = correct_answer if correct_ans_val: # To handle if Quiz-type is Short-Response correct_answer = map(int,correct_ans_val) # Convert list of unicode ele to list of int ele correct_ans_val_list = [options[each_val-1] for each_val in correct_answer] create_gattribute(quiz_item_node._id, correct_answer_AT, correct_ans_val_list) # thread_obj = create_thread_for_node(request,group_id, quiz_item_node) quiz_item_node.reload() quiz_item_node.status = u"PUBLISHED" quiz_item_node.save(groupid=group_id) # Create a thread for QuizItem also. Can be used in preview # Create thread node thread_node = create_thread_for_node(request,group_id, quiz_item_node) if "QuizItemEvent" in quiz_item_node.member_of_names_list: return_url = request.POST.get("return_url") # print "\n\n return_url", return_url, type(return_url) if return_url: return HttpResponseRedirect(reverse(return_url, kwargs={'group_id': group_id})) if quiz_node: quiz_node.collection_set.append(quiz_item_node._id) quiz_node.save(groupid=group_id) return HttpResponseRedirect(reverse('quiz', kwargs={'group_id': group_id})) else: if node_id: if quiz_item_node: quiz_item_node.get_neighbourhood(quiz_item_node.member_of) context_variables.update({'node': quiz_item_node, 'groupid':group_id, 'group_id': group_id, 'translated_node': translated_node, 'question_content': question_content, 'options_list': options_list }) return render_to_response("ndf/quiz_item_create_edit.html", context_variables, context_instance=RequestContext(request) )
def create_edit_term(request, group_id, node_id=None): # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) context_variables = { 'title': title, 'group_id': group_id, 'groupid': group_id } # To list all term instances terms_list = node_collection.find({'_type': 'GSystem', 'member_of': {'$all': [ObjectId(term_GST._id), ObjectId(topic_GST._id)]}, 'group_set': ObjectId(group_id) }).sort('name', 1) nodes_list = [] for each in terms_list: nodes_list.append(str((each.name).strip().lower())) if node_id: term_node = node_collection.one({'_id': ObjectId(node_id)}) else: term_node = node_collection.collection.GSystem() if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) term_node.save(is_changed=get_node_common_fields(request, term_node, group_id, term_GST),groupid=group_id) get_node_metadata(request,term_node,term_GST) return HttpResponseRedirect(reverse('term_details', kwargs={'group_id': group_id, 'node_id': term_node._id })) else: if node_id: term_node,ver=get_page(request,term_node) term_node.get_neighbourhood(term_node.member_of) context_variables['node'] = term_node context_variables['groupid']=group_id context_variables['group_id']=group_id context_variables['nodes_list'] = json.dumps(nodes_list) else: context_variables['nodes_list'] = json.dumps(nodes_list) return render_to_response("ndf/term_create_edit.html", context_variables, context_instance=RequestContext(request) )
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None try: group_id = ObjectId(group_id) #group_id is a valid ObjectId except: group_name, group_id = get_group_name_id( group_id ) #instead of group_id the name of the object is passed via URL to the function app_set = "" title = "" #Stores the name of the type of event such as Meeting, Inauguration, etc. session_of = "" module = "" Add = "" announced_course = "" batch = "" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" group_inverse_rel_id = [] Group_type = node_collection.one( {'_id': ObjectId(group_id)} ) #instance of the group object in which the event is created e.g. "home" is a group for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({ '_type': 'GSystem', '_id': { '$in': group_inverse_rel_id } }) Eventtype = 'Eventtype' if Group_name: if (any(unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype = 'CollegeEvents' else: Eventtype = 'Eventtype' Glisttype = node_collection.find({"_type": "GSystemType", "name": "GList"}) Event_Types = node_collection.one( { "member_of": ObjectId(Glisttype[0]["_id"]), "name": Eventtype }, {'collection_set': 1} ) #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ... app_collection_set = [ ] #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append( node_collection.one({"_id": eachset}, { '_id': 1, 'name': 1, 'type_of': 1 })) iteration = request.POST.get("iteration", "") if iteration == "": iteration = 1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one( { '_type': "GSystemType", '_id': ObjectId(app_set_id) }, { 'name': 1, 'type_of': 1 } ) #GSystemType Object for the event corresponding to app_set_id e.g. Meeting title = event_gst.name event_gs = node_collection.collection.GSystem( ) #create a new GSystem Object for the Event event_gs.member_of.append( event_gst._id) #event_gs is a member_of event_gst if app_set_instance_id: #app_set_instance_id is the objectid of the event object which is already created event_gs = node_collection.one({ '_type': "GSystem", '_id': ObjectId(app_set_instance_id) }) property_order_list = get_property_order_with_value( event_gs ) #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc.. if request.method == "POST": print "#####################" print request.POST.getlist(u'event_coordinator') print "#####################" # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name", "")) == "": if i > 0: field_value = request.POST.get('start_time' + "_" + str(i), '') else: field_value = request.POST.get('start_time', '') # print "----------------Field Value-----------" # print field_value if event_gst.name == "Exam": name = "Exam" + "--" + slugify( request.POST.get("batch_name", "")) + "--" + field_value else: name = "Class" + "--" + slugify( request.POST.get("course_name", "")) + "--" + field_value # print "-----------------Name------------------" # print name event_gs.name = name event_gs.save(is_changed=is_changed, groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: print "##########################" print "field_set:" print field_set print "##########################s" # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key( '_id' ): #Implies field_set is not a basefield but is an AT/RT field_instance = node_collection.one( {'_id': field_set['_id']} ) #field_instance is an instance for AT or RT e.g. start_time field_instance_type = type(field_instance) if field_instance_type in [ AttributeType, RelationType ]: if field_instance["name"] == "attendees": continue field_data_type = field_set[ 'data_type'] #data type of AT/RT e.g. datetime.datetime for start_time # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[ field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance[ "altnames"] content_org = "" tags = "" field_value = save_file( field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance[ "validators"]: if i > 0: field_value = request.POST.get( field_instance["name"] + "_" + str(i)) else: field_value = request.POST[ field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[ field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in [ "12_passing_year", "degree_passing_year" ]: #, "registration_year"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in [ "dob", "registration_date" ]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute( event_gs._id, node_collection.collection. AttributeType(field_instance), field_value) # print "--------------------------------------------------------------------------------------------------" # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name else: #field_instance_type == RelationType field_value_list = request.POST.getlist( field_instance["name"]) # print "#######################" # print field_value_list # print "#######################" # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate( field_value_list): print "#######" print field_value print "#######" field_value = parse_template_data( ObjectId, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: event_gs_triple_instance = create_grelation( event_gs._id, node_collection.collection. RelationType(field_instance), field_value_list) # if isinstance(event_gs_triple_instance, list): # print "\n" # for each in event_gs_triple_instance: # print " event_gs_triple_instance: ", each._id, " -- ", each.name # print "\n" # else: # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name #End of for loop on property_order_list # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i == ((int(iteration)) - 1): #code to send mail to every one return HttpResponseRedirect( reverse('event_app_instance_detail', kwargs={ 'group_id': group_id, "app_set_id": app_set_id, "app_set_instance_id": event_gs._id })) else: to_user_list = [] event_organizer_str = "" event_coordinator_str = "" event_organized_by = [] event_attendees = [] event_coordinator = [] event_node = node_collection.one( {'_id': ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('event_organised_by') in i.keys(): event_organized_by = i['event_organised_by'] if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] if unicode('event_coordinator') in i.keys(): event_coordinator = i['event_coordinator'] event_url = "/" + str(group_id) + "/event/" + str( app_set_id) + "/" + str(event_node._id) site = Site.objects.get(pk=1) site = site.name.__str__() event_link = "http://" + site + event_url event_organized_by_cur = node_collection.find( {"_id": { '$in': event_organized_by }}) event_coordinator_cur = node_collection.find( {"_id": { '$in': event_coordinator }}) for i in event_coordinator_cur: event_coordinator_str = event_coordinator_str + i.name + " " for i in event_organized_by_cur: event_organizer_str = event_coordinator_str + i.name + " " for j in event_attendees: auth = node_collection.one({"_id": ObjectId(j)}) user_obj = User.objects.get(id=auth.created_by) if user_obj not in to_user_list: to_user_list.append(user_obj) render_label = render_to_string( "notification/label.html", { "sender": "metaStudio", "activity": "Event Created", "conjunction": "-" }) if event_organized_by: msg_string = "\n Event is organized by " + str( event_organizer_str) else: msg_string = "" print "--------------------------" print event_node.name print event_node._id print "--------------------------" SALT = '8cd8ef52e8e101574e400365b55e11a6' URL = 'http://test-install.blindsidenetworks.com/bigbluebutton/' createMeeting(event_node.name, event_node._id, 'welcome', 'mPW', 'aPW', SALT, URL, 'www.google.com') url = joinURL(event_node._id, 'user', 'mPW', SALT, URL) event_node.url = unicode(url) event_node.save() # url_create = createMeetingURL(event_node.name, event_node._id, 'aPW', 'mPW', 'welcome', 'www.google.com', SALT , URL); print "##########" print event_node.url print "##########" # bbb_start(event_node.name, event_node._id) message_string = "Invitation for Event" + " " + str( event_node.name ) + msg_string + "\n Event will be co-ordinated by " + str( event_coordinator_str ) + "\n- Please click [[" + event_link + "][here]] to view the details of the event" message_string = "Hello World" notification.create_notice_type( render_label, message_string, "notification" ) ##This is sent via email to all attendees in the group notification.send(to_user_list, render_label, {"from_user": "******"}) return HttpResponseRedirect( reverse('event_app_instance_detail', kwargs={ 'group_id': group_id, "app_set_id": app_set_id, "app_set_instance_id": event_node._id })) event_attendees = request.POST.getlist('has_attendees', '') event_gs.get_neighbourhood(event_gs.member_of) course = [] val = False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch = node_collection.one({ '_type': "GSystem", '_id': ObjectId(i['event_has_batch'][0]) }) batch_relation = node_collection.one( { '_type': "GSystem", '_id': ObjectId(batch._id) }, {'relation_set': 1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course = node_collection.one({ "_type": "GSystem", '_id': ObjectId(i['has_course'][0]) }) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course = node_collection.one({ "_type": "GSystem", '_id': ObjectId(i['announced_for'][0]) }) if unicode('session_of') in i.keys(): session_of = node_collection.one({ '_type': "GSystem", '_id': ObjectId(i['session_of'][0]) }) module = node_collection.one({ '_type': "GSystem", '_id': { '$in': session_of.prior_node } }) event_gs.event_coordinator Mis_admin = node_collection.one({"_type": "Group", "name": "MIS_admin"}) if Mis_admin: Mis_admin_list = Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add = "Allow" else: Add = "Stop" else: Add = "Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template = "ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list, 'Add': Add } if app_set_instance_id: event_detail = {} events = {} if event_gs.event_coordinator: event_detail["cordinatorname"] = str( event_gs.event_coordinator[0].name) event_detail["cordinatorid"] = str( event_gs.event_coordinator[0]._id) events["cordinator"] = event_detail if announced_course: event_detail["course"] = str(announced_course.name) event_detail["course_id"] = str(announced_course._id) events["course"] = event_detail event_detail = {} if batch: event_detail["batchname"] = str(batch.name) event_detail["batchid"] = str(batch._id) events["batch"] = event_detail event_detail = {} if session_of: event_detail["sessionname"] = str(session_of.name) event_detail["sessionid"] = str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str( i['course_structure_minutes']) events["session"] = event_detail event_detail = {} if module: event_detail["Modulename"] = str(module.name) event_detail["Moduleid"] = str(module._id) events["Module"] = event_detail context_variables['node'] = event_gs context_variables['edit_details'] = events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance=RequestContext(request))
def theme_topic_create_edit(request, group_id, app_set_id=None): ##################### # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) ###################### nodes_dict = [] create_edit = True themes_hierarchy = False themes_list_items = "" themes_cards = "" title = "" node = "" theme_topic_node = "" drawers = None drawer = None app_id = None nodes_list = [] parent_nodes_collection = "" translate = request.GET.get('translate', '') app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)}) if app_GST._id != theme_GST._id: app_obj = node_collection.one({'_id': ObjectId(app_GST.member_of[0])}) else: app_obj = theme_GST if app_obj: app_id = app_obj._id shelves = [] shelf_list = {} auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if auth: has_shelf_RT = node_collection.one({ '_type': 'RelationType', 'name': u'has_shelf' }) shelf = triple_collection.find({ '_type': 'GRelation', 'subject': ObjectId(auth._id), 'relation_type': has_shelf_RT._id }) shelf_list = {} if shelf: for each in shelf: shelf_name = node_collection.one( {'_id': ObjectId(each.right_subject)}) shelves.append(shelf_name) shelf_list[shelf_name.name] = [] for ID in shelf_name.collection_set: shelf_item = node_collection.one({'_id': ObjectId(ID)}) shelf_list[shelf_name.name].append(shelf_item.name) else: shelves = [] if request.method == "POST": if app_GST: create_edit = True themes_list_items = "" root_themes = [] root_themes_id = [] nodes_list = [] name = request.POST.get('name') collection_list = request.POST.get('collection_list', '') prior_node_list = request.POST.get('prior_node_list', '') teaches_list = request.POST.get('teaches_list', '') assesses_list = request.POST.get('assesses_list', '') # To find the root nodes to maintain the uniquness while creating and editing themes nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes_id.append(each._id) if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == "true": # For creating new themes & Topics themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True if name or translate == "true": if not name.upper() in (theme_name.upper() for theme_name in root_themes ) or translate == "true": if translate != "true": theme_topic_node = node_collection.collection.GSystem( ) # get_node_common_fields(request, theme_topic_node, group_id, app_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, app_GST), groupid=group_id) if translate == "true": global list_trans_coll list_trans_coll = [] coll_set1 = get_coll_set(app_GST._id) for each in coll_set1: theme_topic_node = node_collection.collection.GSystem( ) if "Theme" in each.member_of_names_list: app_obj = theme_GST if "theme_item" in each.member_of_names_list: app_obj = theme_item_GST if "topic" in each.member_of_names_list: app_obj = topic_GST theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, app_obj, each), groupid=group_id) coll_set_dict[each._id] = theme_topic_node._id relation_type = node_collection.one({ '_type': 'RelationType', 'name': 'translation_of' }) # grelation=collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=each._id # grelation.right_subject=theme_topic_node._id # grelation.name=u"" # grelation.save() gr_node = create_grelation( each._id, relation_type, theme_topic_node._id) for each in coll_set1: #if "Theme" in each.member_of_names_list: if each.collection_set: for collset in each.collection_set: p = coll_set_dict[each._id] parent_node = node_collection.one( {'_id': ObjectId(str(p))}) n = coll_set_dict[collset] sub_node = node_collection.one( {'_id': ObjectId(str(n))}) parent_node.collection_set.append( sub_node._id) parent_node.save(groupid=group_id) # To return themes card view for listing theme nodes after creating new Themes nodes.rewind() nodes_dict = nodes else: themes_list_items = False create_edit = False themes_hierarchy = True theme_topic_node = node_collection.one( {'_id': ObjectId(app_GST._id)}) # For edititng themes if theme_GST._id in app_GST.member_of and translate != "true": # To find themes uniqueness within the context of its parent Theme collection, while editing theme name root_themes = [] nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: root_themes.append(each.name) if name: if name.upper() != theme_topic_node.name.upper(): if not name.upper() in ( theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_GST), groupid=group_id) else: theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_GST), groupid=group_id) if translate != "true": # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) # End of storing collection title = theme_GST.name nodes.rewind() nodes_dict = nodes # This will return to Themes Hierarchy themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True elif theme_item_GST._id in app_GST.member_of and translate != "true": title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) # Code for fetching drawer2 for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k)}) dict2.append(obj) dict_drawer['2'] = dict2 # drawers = dict_drawer # End of code for drawer2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme item nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) if not prior_theme_collection: root_nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for k in root_nodes: if app_GST._id in k.collection_set: root_themes = [] root_themes_id = [] for l in k.collection_set: objs = node_collection.one( {'_id': ObjectId(l)}) root_themes.append(objs.name) root_themes_id.append(objs._id) # End of finding unique theme names for editing name # For adding a sub-theme-items and maintianing their uniqueness within their context nodes_list = [] for each in app_GST.collection_set: sub_theme = node_collection.one( {'_id': ObjectId(each)}) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes if name: if name.upper() != theme_topic_node.name.upper(): # If "Name" has changed if theme_topic_node._id in root_themes_id: # If editing node in root theme items if not name.upper() in ( theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) else: # If editing theme item in prior_theme_collection hierarchy if not name.upper() in (theme_name.upper( ) for theme_name in prior_theme_collection): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) else: # If name not changed but other fields has changed theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) if translate != "true" and collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) # End of storing collection # This will return to Themes items edit if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False # For editing topics elif topic_GST._id in app_GST.member_of: root_topics = [] nodes_list = [] # To find the root nodes to maintain the uniquness while creating and editing topics nodes = node_collection.find({ 'member_of': { '$all': [topic_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_topics.append(each.name) # End of finding the root nodes if name: if theme_topic_node.name != name: topic_name = theme_topic_node.name if not name.upper() in ( theme_name.upper() for theme_name in root_topics): theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) elif topic_name.upper() == name.upper(): theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) else: theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) if collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append( node_id) i = i + 1 theme_topic_node.save(groupid=group_id) title = topic_GST.name # To fill the metadata info while creating and editing topic node metadata = request.POST.get("metadata_info", '') if metadata: # Only while metadata editing if metadata == "metadata": if theme_topic_node: get_node_metadata(request, theme_topic_node) # End of filling metadata if prior_node_list != '': theme_topic_node.prior_node = [] prior_node_list = prior_node_list.split(",") i = 0 while (i < len(prior_node_list)): node_id = ObjectId(prior_node_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.prior_node.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) if teaches_list != '': teaches_list = teaches_list.split(",") create_grelation_list(theme_topic_node._id, "teaches", teaches_list) if assesses_list != '': assesses_list = assesses_list.split(",") create_grelation_list(theme_topic_node._id, "assesses", assesses_list) # This will return to edit topic if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False else: app_node = None nodes_list = [] app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)}) # print "\napp_GST in else: ",app_GST.name,"\n" if app_GST: # For adding new Theme & Topic if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == True: print "22222" title = app_GST.name node = "" root_themes = [] # To find the root nodes to maintain the uniquness while creating new themes nodes = node_collection.find({ 'member_of': { '$all': [app_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes = json.dumps(root_themes) nodes_list = root_themes # End of finding unique root level Themes else: if theme_GST._id in app_GST.member_of: title = "Theme" node = app_GST prior_theme_collection = [] parent_nodes_collection = "" drawer = [] # End of editing Themes # For editing theme item if theme_item_GST._id in app_GST.member_of: title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k)}) dict2.append(obj) dict_drawer['2'] = dict2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme name nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) # End of finding unique theme names for editing name # For adding a sub-themes and maintianing their uniqueness within their context for each in app_GST.collection_set: sub_theme = node_collection.one( {'_id': ObjectId(each)}) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes # for editing topic elif topic_GST._id in app_GST.member_of: title = topic_GST.name node = app_GST prior_theme_collection = [] parent_nodes_collection = "" node.get_neighbourhood(node.member_of) # To find topics uniqueness within the context of its parent Theme item collection, while editing topic name nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) # End of finding unique theme names for editing name if translate: global list_trans_coll list_trans_coll = [] trans_coll_list = get_coll_set(str(app_GST._id)) print LANGUAGES return render_to_response( "ndf/translation_page.html", { 'group_id': group_id, 'groupid': group_id, 'title': title, 'node': app_GST, 'lan': LANGUAGES, 'list1': trans_coll_list }, context_instance=RequestContext(request)) if title == "Topic": return render_to_response("ndf/node_edit_base.html", { 'group_id': group_id, 'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'shelf_list': shelf_list, 'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy, 'app_id': app_id, 'appId': app._id, 'nodes_list': nodes_list, 'title': title, 'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id, 'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items, 'nodes': nodes_dict, 'lan': LANGUAGES }, context_instance=RequestContext(request)) return render_to_response("ndf/theme.html", { 'group_id': group_id, 'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'theme_GST': theme_GST, 'theme_GST': theme_GST, 'shelf_list': shelf_list, 'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy, 'app_id': app_id, 'appId': app._id, 'nodes_list': nodes_list, 'title': title, 'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id, 'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items, 'nodes': nodes_dict, 'lan': LANGUAGES }, context_instance=RequestContext(request))
def video_edit(request,group_id,_id): # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) vid_node = node_collection.one({"_id": ObjectId(_id)}) title = GST_VIDEO.name video_obj=request.GET.get("vid_id","") group_obj = node_collection.one({'_id': ObjectId(group_id)}) ce_id = request.GET.get('course_event_id') course_tab_title = request.POST.get("course_tab_title",'') res = request.GET.get('res') if request.method == "POST": # get_node_common_fields(request, vid_node, group_id, GST_VIDEO) vid_node.save(is_changed=get_node_common_fields(request, vid_node, group_id, GST_VIDEO),groupid=group_id) thread_create_val = request.POST.get("thread_create",'') course_tab_title = request.POST.get("course_tab_title",'') # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"}) if thread_create_val == "Yes": create_gattribute(vid_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request,group_id, vid_node) else: create_gattribute(vid_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if help_info_page and u"None" not in help_info_page: has_help_rt = node_collection.one({'_type': "RelationType", 'name': "has_help"}) try: help_info_page = map(ObjectId, help_info_page) create_grelation(vid_node._id, has_help_rt,help_info_page) except Exception as invalidobjectid: # print "\n\n ERROR -------- ",invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(vid_node._id,"has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id","") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=vid_node._id, node_id=each_grel_id, deletion_type=0 ) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg if "CourseEventGroup" not in group_obj.member_of_names_list: get_node_metadata(request,vid_node) teaches_list = request.POST.get('teaches_list', '') # get the teaches list assesses_list = request.POST.get('assesses_list', '') # get the teaches list if teaches_list !='': teaches_list=teaches_list.split(",") create_grelation_list(vid_node._id,"teaches",teaches_list) if assesses_list !='': assesses_list=assesses_list.split(",") create_grelation_list(vid_node._id,"assesses",assesses_list) return HttpResponseRedirect(reverse('video_detail', kwargs={'group_id': group_id, '_id': vid_node._id})) else: vid_node.status = u"PUBLISHED" vid_node.save() if course_tab_title: if course_tab_title == "raw material": course_tab_title = "raw_material" return HttpResponseRedirect(reverse('course_'+course_tab_title + '_detail', kwargs={'group_id': group_id, 'node_id': str(vid_node._id)})) return HttpResponseRedirect(reverse('course_about', kwargs={'group_id': group_id})) # url = "/"+ str(group_id) +"/?selected="+str(vid_node._id)+"#view_page" # return HttpResponseRedirect(url) else: vid_col = node_collection.find({'member_of': GST_VIDEO._id,'group_set': ObjectId(group_id)}) nodes_list = [] for each in vid_col: nodes_list.append(str((each.name).strip().lower())) return render_to_response("ndf/video_edit.html", { 'node': vid_node, 'title': title, 'group_id': group_id, 'groupid':group_id, 'video_obj':video_obj, 'nodes_list':nodes_list, 'ce_id': ce_id, 'res': res, 'course_tab_title':course_tab_title }, context_instance=RequestContext(request) )
def create_entries(request, group_id): ''' for creating a new bibtex entry_list ''' ins_objectid = ObjectId() if ins_objectid.is_valid(group_id) is False: group_ins = collection.Node.find_one({ '_type': "Group", "name": group_id }) auth = collection.Node.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if group_ins: group_id = str(group_ins._id) else: auth = collection.Node.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if auth: group_id = str(auth._id) else: pass ''' for retreiving the fields of a particular bibtex entry ''' num = int(request.GET.get('num')) entry = Bibtex_entries[num] for name, value in entry.iteritems(): title = name list_item = value GST_BIBTEX = collection.Node.one({'_type': 'GSystemType', 'name': title}) GST_ENTRY = collection.Node.one({ '_type': 'AttributeType', 'name': 'BibTex_entry' }) GST_LIST = collection.Node.one({ '_type': 'AttributeType', 'name': 'entry_list' }) GST_CITATION = collection.Node.one({ '_type': 'AttributeType', 'name': 'Citation' }) context_variables = { 'title': title, 'group_id': group_id, 'groupid': group_id, 'list_item': list_item, 'num': num } entry_node = collection.GSystem() cite = "" i = 0 value = "" if request.method == "POST": name = request.POST.get("name") entry_node.name = name citation_key = request.POST.get("citation_key") var = "@" + title + "{" + citation_key value += "name$" + name + "%citation_key$" + citation_key + "%" for each in list_item: c = request.POST.get(each, "") var += " , " + each + " = " + " { " + c + " }" value += each + "$" + c + "%" i = i + 1 if (each == 'author' and c != ""): cite += c + "." if (each == 'title' and c != ""): cite += c + '.' if (each == 'year' and c != ""): cite += "(" + c + ") " if (each == 'publisher' and c != ""): cite += "publisher:" + c + "," if (each == 'volume' and c != ""): cite += "volume:" + c + "," if (each == 'edition' and c != ""): cite += "edition:" + c + "," if (each == 'pages' and c != ""): cite += "page " + c + "," var += "}" get_node_common_fields(request, entry_node, group_id, GST_BIBTEX) entry_node.status = u'PUBLISHED' entry_node.save() ''' creating a GAttribute of AttributeType BibTex_entry for the already created GSystem ''' GST_current = collection.Node.one({'name': name, 'member_of': title}) Bibtex_entry = collection.GAttribute() Bibtex_entry.name = unicode(name) Bibtex_entry.subject = ObjectId(entry_node._id) Bibtex_entry.attribute_type = GST_ENTRY Bibtex_entry.object_value = unicode(var) Bibtex_entry.save() ''' creating a GAttribute of AttributeType Citation for the already created GSystem ''' cite_key = collection.GAttribute() cite_key.name = unicode(name) cite_key.subject = ObjectId(entry_node._id) cite_key.attribute_type = GST_CITATION cite_key.object_value = unicode(cite) cite_key.save() ''' creating a GAttribute of AttributeType entry_list for the already created GSystem ''' entry_list = collection.GAttribute() entry_list.name = unicode(name) entry_list.subject = ObjectId(entry_node._id) entry_list.attribute_type = GST_LIST entry_list.object_value = unicode(value) entry_list.save() return HttpResponseRedirect( reverse('view_entry', kwargs={ 'group_id': group_id, 'node_id': GST_BIBTEX._id })) else: return render_to_response("ndf/create_edit_entries.html", context_variables, context_instance=RequestContext(request))