Beispiel #1
0
def list_modules(request, group_id):
    '''
    listing of modules
    '''
    all_modules = GSystem.query_list(group_id, 'Module', request.user.id)
    template = "ndf/explore_2017.html"

    context_variable = {
                        'title': 'Modules', 'doc_cur': all_modules,
                        'group_id': group_id, 'groupid': group_id,
                        'card': 'ndf/horizontal_card.html', 'card_url_name': 'module_detail'
                    }

    return render_to_response(
        template,
        context_variable,
        context_instance=RequestContext(request))
Beispiel #2
0
def list_modules(request, group_id):
    '''
    listing of modules
    '''
    all_modules = GSystem.query_list(group_id, 'Module', request.user.id)
    template = "ndf/explore_2017.html"

    context_variable = {
                        'title': 'Modules', 'doc_cur': all_modules,
                        'group_id': group_id, 'groupid': group_id,
                        'card': 'ndf/horizontal_card.html', 'card_url_name': 'module_detail'
                    }

    return render_to_response(
        template,
        context_variable,
        context_instance=RequestContext(request))
Beispiel #3
0
def api_get_gs_nodes(request):

    get_parameters_dict = request.GET.dict()

    if not get_parameters_dict:
        aggregated_dict = gst_api_fields_dict.copy()
        aggregated_dict.update(api_name_model_name_dict)
        aggregated_dict.pop('_id')

        query_parameters_dict = {
            'Fields':
            aggregated_dict.keys(),
            'Attributes':
            node_collection.find({
                '_type': 'AttributeType'
            }).distinct('name'),
            'Relations':
            node_collection.find({
                '_type': 'RelationType'
            }).distinct('name')
        }
        return HttpResponse(json.dumps(query_parameters_dict, indent=4),
                            content_type='application/json')

    # GET: api/v1/<group_id>/<files>/<nroer_team>/
    exception_occured = ''
    oid_name_dict = {}
    gst_id = None
    # try:
    #     group_id = ObjectId(group_name_or_id)
    # except Exception as e:
    #     group_name, group_id = get_group_name_id(group_name_or_id)
    #     oid_name_dict[group_id] = group_name

    gsystem_structure_dict = GSystem.structure
    gsystem_keys = gsystem_structure_dict.keys()

    gst_all_fields_dict = {i: 1 for i in gsystem_keys}

    query_dict = {
        '_type': 'GSystem',
        'status': u'PUBLISHED',
        'access_policy': 'PUBLIC',
        # 'group_set': ObjectId(group_id),
        # 'member_of': ObjectId(gst_id),
        # 'created_by': user_id,
    }

    sample_gs = GSystem()
    attributes = {}

    # GET parameters:
    get_created_by = request.GET.get('created_by', None)
    if get_created_by:
        username_or_id_int = 0
        try:
            username_or_id_int = int(get_created_by)
        except Exception as e:
            pass

        auth_obj = node_collection.one({
            '_type':
            u'Author',
            '$or': [{
                'name': unicode(get_created_by)
            }, {
                'created_by': username_or_id_int
            }]
        })
        if auth_obj:
            oid_name_dict[auth_obj._id] = auth_obj.name
            # user_id = auth_obj.created_by
            get_parameters_dict['created_by'] = auth_obj.created_by
        else:
            return HttpResponse('Requested user does not exists.',
                                content_type='text/plain')

    get_resource_type = request.GET.get('resource_type', None)
    if get_resource_type:
        gst_name, gst_id = GSystemType.get_gst_name_id(get_resource_type)
        oid_name_dict[gst_id] = gst_name
        get_parameters_dict['member_of'] = [gst_id]
        attributes = sample_gs.get_possible_attributes([gst_id])

    get_workspace = request.GET.get('workspace', None)
    if get_workspace:
        group_name, group_id = Group.get_group_name_id(get_workspace)
        oid_name_dict[group_id] = group_name
        get_parameters_dict['group_set'] = [group_id]

    for key, val in get_parameters_dict.iteritems():
        stripped_key = key.split('.')[0]
        if stripped_key in gsystem_keys:
            query_dict.update({
                key: ({
                    '$regex': val,
                    '$options': 'i'
                } if isinstance(gsystem_structure_dict[stripped_key],
                                basestring or unicode) else val)
            })

        elif stripped_key in gst_attributes(gst_id):
            query_dict.update({
                ('attribute_set.' + stripped_key): {
                    '$regex': val,
                    '$options': 'i'
                }
            })

    # print "query_dict: ", query_dict

    human = eval(request.GET.get('human', '1'))

    gst_fields = gst_api_fields_dict if human else gst_all_fields_dict

    all_resources = node_collection.find(query_dict, gst_fields)

    if human:
        gst_fields = gst_api_fields_dict

        # converting ids to human readable names:
        # Django User:
        user_fields = ['created_by', 'modified_by', 'contributors']
        all_users = []
        for each_field in user_fields:
            all_users += all_resources.distinct(each_field)
        all_users = list(set(all_users))

        userid_name_dict_cur = node_collection.find(
            {
                '_type': u'Author',
                'created_by': {
                    '$in': all_users
                }
            }, {
                'name': 1,
                'created_by': 1,
                '_id': 0
            })
        userid_name_dict = {
            i['created_by']: i['name']
            for i in userid_name_dict_cur
        }

        # Mongo ids
        oid_fields = [
            k for k, v in gsystem_structure_dict.iteritems()
            if v in [bson.objectid.ObjectId, [bson.objectid.ObjectId]]
        ]
        all_oid_list = []
        for each_field in oid_fields:
            all_oid_list += all_resources.distinct(each_field)
        all_oid_list = list(set(all_oid_list))

        oid_name_dict_cur = node_collection.find(
            {'_id': {
                '$in': all_oid_list
            }}, {'name': 1})
        oid_name_dict = {i['_id']: i['name'] for i in oid_name_dict_cur}

        python_cur_list = []
        python_cur_list_append = python_cur_list.append
        for each_gs in all_resources:

            # attaching attributes:
            # NEEDS to optimize.
            for key, value in each_gs.get_possible_attributes(
                    each_gs.member_of).iteritems():
                each_gs[key] = value['data_type']
                each_gs[key] = value['object_value']

            # mapping user id to username.
            for each_field in user_fields:
                each_gs[each_field] = [
                    userid_name_dict.get(i, i) for i in each_gs[each_field]
                ] if isinstance(each_gs[each_field],
                                list) else userid_name_dict.get(
                                    each_gs[each_field], each_gs[each_field])

            # mapping mongo _id to name.
            for each_field in oid_fields:
                each_gs[each_field] = [
                    oid_name_dict.get(i, i) for i in each_gs[each_field]
                ] if isinstance(each_gs[each_field],
                                list) else oid_name_dict[each_gs[each_field]]

            python_cur_list_append(each_gs)

        json_result = json.dumps(python_cur_list,
                                 cls=NodeJSONEncoder,
                                 sort_keys=True,
                                 indent=4)

    else:
        json_result = dumps(all_resources, sort_keys=True, indent=4)

    return HttpResponse(json_result, content_type='application/json')
Beispiel #4
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    print "inside unit_create_edit", parent_group_name, parent_group_id
    print "request path", request.method
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        print "group names :", all_groups_names
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }

        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,
                                    tags=tags,
                                    author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if resource_name:
            unit_node['project_config'].update(
                {"resource_name": resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"resource_name": "Resources"})
        else:
            unit_node['project_config'].update(
                {"resource_name": "Resource Name"})

        if blog_name:
            unit_node['project_config'].update({"blog_name": blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"blog_name": "e-Notes"})
        else:
            unit_node['project_config'].update({"blog_name": "blog Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_content', kwargs={'group_id': unit_node._id}))
Beispiel #5
0
def api_get_gs_nodes(request):

    get_parameters_dict = request.GET.dict()

    if not get_parameters_dict:
        aggregated_dict = gst_api_fields_dict.copy()
        aggregated_dict.update(api_name_model_name_dict)
        aggregated_dict.pop('_id')

        query_parameters_dict = {
                                    'Fields': aggregated_dict.keys(),
                                    'Attributes': node_collection.find({'_type': 'AttributeType'}).distinct('name'),
                                    'Relations': node_collection.find({'_type': 'RelationType'}).distinct('name')
                                }
        return HttpResponse(json.dumps(query_parameters_dict, indent=4), content_type='application/json')


    # GET: api/v1/<group_id>/<files>/<nroer_team>/
    exception_occured = ''
    oid_name_dict = {}
    gst_id = None
    # try:
    #     group_id = ObjectId(group_name_or_id)
    # except Exception as e:
    #     group_name, group_id = get_group_name_id(group_name_or_id)
    #     oid_name_dict[group_id] = group_name

    gsystem_structure_dict = GSystem.structure
    gsystem_keys = gsystem_structure_dict.keys()

    gst_all_fields_dict = {i: 1 for i in gsystem_keys}

    query_dict = {
                    '_type': 'GSystem',
                    'status': u'PUBLISHED',
                    'access_policy': 'PUBLIC',
                    # 'group_set': ObjectId(group_id),
                    # 'member_of': ObjectId(gst_id),
                    # 'created_by': user_id,
                }

    sample_gs = GSystem()
    attributes = {}

    # GET parameters:
    get_created_by = request.GET.get('created_by', None)
    if get_created_by:
        username_or_id_int = 0
        try:
            username_or_id_int = int(get_created_by)
        except Exception as e:
            pass

        auth_obj = node_collection.one({'_type': u'Author', '$or': [{'name': unicode(get_created_by)}, {'created_by': username_or_id_int} ] })
        if auth_obj:
            oid_name_dict[auth_obj._id] = auth_obj.name
            # user_id = auth_obj.created_by
            get_parameters_dict['created_by'] = auth_obj.created_by
        else:
            return HttpResponse('Requested user does not exists.', content_type='text/plain')

    get_resource_type = request.GET.get('resource_type', None)
    if get_resource_type:
        gst_name, gst_id = GSystemType.get_gst_name_id(get_resource_type)
        oid_name_dict[gst_id] = gst_name
        get_parameters_dict['member_of'] = [gst_id]
        attributes = sample_gs.get_possible_attributes([gst_id]) 

    get_workspace = request.GET.get('workspace', None)
    if get_workspace:
        group_name, group_id = Group.get_group_name_id(get_workspace)
        oid_name_dict[group_id] = group_name
        get_parameters_dict['group_set'] = [group_id]

    for key, val in get_parameters_dict.iteritems():
        stripped_key = key.split('.')[0]
        if stripped_key in gsystem_keys:
            query_dict.update({ key: ({'$regex': val, '$options': 'i'} if isinstance(gsystem_structure_dict[stripped_key], basestring or unicode) else val) })

        elif stripped_key in gst_attributes(gst_id):
            query_dict.update({('attribute_set.' + stripped_key): {'$regex': val, '$options': 'i'}})

    # print "query_dict: ", query_dict

    human = eval(request.GET.get('human', '1'))

    gst_fields = gst_api_fields_dict if human else gst_all_fields_dict

    all_resources = node_collection.find(query_dict, gst_fields)

    if human:
        gst_fields = gst_api_fields_dict

        # converting ids to human readable names:
        # Django User:
        user_fields = ['created_by', 'modified_by', 'contributors']
        all_users = []
        for each_field in user_fields:
            all_users += all_resources.distinct(each_field)
        all_users = list(set(all_users))

        userid_name_dict_cur = node_collection.find({'_type': u'Author', 'created_by': {'$in': all_users}}, {'name': 1, 'created_by': 1, '_id': 0})
        userid_name_dict = {i['created_by']: i['name'] for i in userid_name_dict_cur}

        # Mongo ids
        oid_fields = [ k for k, v in gsystem_structure_dict.iteritems() if v in [bson.objectid.ObjectId, [bson.objectid.ObjectId]] ]
        all_oid_list = []
        for each_field in oid_fields:
            all_oid_list += all_resources.distinct(each_field)
        all_oid_list = list(set(all_oid_list))

        oid_name_dict_cur = node_collection.find({'_id': {'$in': all_oid_list}}, {'name': 1})
        oid_name_dict = {i['_id']: i['name'] for i in oid_name_dict_cur}

        python_cur_list = []
        python_cur_list_append = python_cur_list.append
        for each_gs in all_resources:

            # attaching attributes:
            # NEEDS to optimize.
            for key, value in each_gs.get_possible_attributes(each_gs.member_of).iteritems():
                each_gs[key] = value['data_type']
                each_gs[key] = value['object_value']

            # mapping user id to username.
            for each_field in user_fields:
                each_gs[each_field] = [userid_name_dict.get(i, i) for i in each_gs[each_field]] if isinstance(each_gs[each_field], list) else userid_name_dict.get(each_gs[each_field], each_gs[each_field])

            # mapping mongo _id to name.
            for each_field in oid_fields:
                each_gs[each_field] = [oid_name_dict.get(i, i) for i in each_gs[each_field]] if isinstance(each_gs[each_field], list) else oid_name_dict[each_gs[each_field]]

            python_cur_list_append(each_gs)

        json_result = json.dumps(python_cur_list, cls=NodeJSONEncoder, sort_keys=True, indent=4)

    else:
        json_result = dumps(all_resources, sort_keys=True, indent=4)

    return HttpResponse(json_result, content_type='application/json')
Beispiel #6
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})

        if resource_name:
            unit_node['project_config'].update( {"resource_name":resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"resource_name":"Resources"})
        else:
            unit_node['project_config'].update( {"resource_name":"Resource Name"})

        if blog_name:
            unit_node['project_config'].update( {"blog_name":blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"blog_name":"e-Notes"})
        else:
            unit_node['project_config'].update( {"blog_name":"blog Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_content',
            kwargs={'group_id': unit_node._id}))
Beispiel #7
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {'$in': [unit_id]}
            })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_about',
            kwargs={'group_id': unit_node._id}))
Beispiel #8
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
            '_type': 'GSystem',
            'member_of': gst_module_id,
            'collection_set': {
                '$in': [unit_id]
            }
        })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_gstystem_values(tags=tags,
                                       author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_about', kwargs={'group_id': unit_node._id}))