PageRenderTime 129ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/gnowsys-ndf/gnowsys_ndf/ndf/views/person.py

https://gitlab.com/g66shivam/gstudio
Python | 736 lines | 717 code | 10 blank | 9 comment | 10 complexity | 9f4ef0c9e4b9280ed72924c0da7e9e2b MD5 | raw file
  1. ''' -- imports from python libraries -- '''
  2. # from datetime import datetime
  3. import datetime
  4. import json
  5. ''' -- imports from installed packages -- '''
  6. from django.http import HttpResponseRedirect, HttpResponse # uncomment when to use
  7. from django.http import Http404
  8. from django.shortcuts import render_to_response #, render uncomment when to use
  9. from django.template import RequestContext
  10. from django.template import TemplateDoesNotExist
  11. from django.core.urlresolvers import reverse
  12. from django.contrib.auth.decorators import login_required
  13. from mongokit import IS
  14. try:
  15. from bson import ObjectId
  16. except ImportError: # old pymongo
  17. from pymongo.objectid import ObjectId
  18. ''' -- imports from application folders/files -- '''
  19. from gnowsys_ndf.settings import META_TYPE
  20. from gnowsys_ndf.ndf.models import AttributeType, RelationType
  21. from gnowsys_ndf.ndf.models import node_collection
  22. from gnowsys_ndf.ndf.views.file import save_file
  23. from gnowsys_ndf.ndf.models import NodeJSONEncoder
  24. from gnowsys_ndf.ndf.views.methods import get_node_common_fields, parse_template_data
  25. from gnowsys_ndf.ndf.views.methods import get_widget_built_up_data, get_property_order_with_value,get_execution_time
  26. from gnowsys_ndf.ndf.views.methods import create_gattribute, create_grelation, create_task
  27. from gnowsys_ndf.ndf.views.methods import get_student_enrollment_code
  28. @get_execution_time
  29. def person_detail(request, group_id, app_id=None, app_set_id=None, app_set_instance_id=None, app_name=None):
  30. """
  31. custom view for custom GAPPS
  32. """
  33. auth = None
  34. if ObjectId.is_valid(group_id) is False :
  35. group_ins = node_collection.one({'_type': "Group","name": group_id})
  36. auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  37. if group_ins:
  38. group_id = str(group_ins._id)
  39. else :
  40. # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  41. if auth :
  42. group_id = str(auth._id)
  43. else :
  44. pass
  45. app = None
  46. if app_id is None:
  47. app = node_collection.one({'_type': "GSystemType", 'name': app_name})
  48. if app:
  49. app_id = str(app._id)
  50. else:
  51. app = node_collection.one({'_id': ObjectId(app_id)})
  52. app_name = app.name
  53. # app_name = "mis"
  54. app_set = ""
  55. app_collection_set = []
  56. title = ""
  57. person_gst = None
  58. person_gs = None
  59. nodes = None
  60. nodes_keys = []
  61. node = None
  62. response_dict = {'success': False}
  63. property_order_list = []
  64. widget_for = []
  65. is_link_needed = True # This is required to show Link button on interface that link's Student's/VoluntaryTeacher's node with it's corresponding Author node
  66. univ_list = []
  67. colg_list = []
  68. template_prefix = "mis"
  69. context_variables = {}
  70. if request.user:
  71. if auth is None:
  72. auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
  73. agency_type = auth.agency_type
  74. agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
  75. if agency_type_node:
  76. # for eachset in agency_type_node.collection_set:
  77. # app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  78. #loop replaced by a list comprehension
  79. app_collection_set=[node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}) for eachset in agency_type_node.collection_set]
  80. if app_set_id:
  81. person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)})#, {'name': 1, 'type_of': 1})
  82. title = person_gst.name
  83. column_headers = None
  84. query = {}
  85. college = {}
  86. course = {}
  87. ac_data_set = []
  88. records_list = []
  89. template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_list.html"
  90. if title == "Student":
  91. person_gs = node_collection.collection.GSystem()
  92. person_gs.member_of.append(person_gst._id)
  93. person_gs.get_neighbourhood(person_gs.member_of)
  94. university_gst = node_collection.one({'_type': "GSystemType", 'name': "University"})
  95. mis_admin = node_collection.one({"_type": "Group", "name": "MIS_admin"}, {"_id": 1})
  96. univ_cur = node_collection.find({"member_of": university_gst._id, 'group_set': mis_admin._id}, {'name': 1, "_id": 1})
  97. attr_deg_yr = node_collection.one({'_type': "AttributeType", 'name': "degree_year"}, {'_id': 1})
  98. widget_for = ["name",
  99. attr_deg_yr._id
  100. ]
  101. widget_for = get_widget_built_up_data(widget_for, person_gs)
  102. # for each in univ_cur:
  103. # univ_list.append(each)
  104. #loop replaced by a list comprehension
  105. univ_list=[each for each in univ_cur]
  106. elif title == "Program Officer" or title == "Voluntary Teacher":
  107. query = {
  108. "member_of": person_gst._id,
  109. }
  110. if title == "Program Officer":
  111. res = node_collection.collection.aggregate([
  112. {
  113. '$match': query
  114. }, {
  115. '$project': {
  116. '_id': 0,
  117. 'person_id': "$_id",
  118. 'name': '$name',
  119. 'college':'$relation_set.officer_incharge_of',
  120. 'email_id': '$attribute_set.email_id',
  121. }
  122. },
  123. {
  124. '$sort': {'name': 1}
  125. }
  126. ])
  127. else:
  128. res = node_collection.collection.aggregate([
  129. {
  130. '$match': query
  131. }, {
  132. '$project': {
  133. '_id': 0,
  134. 'person_id': "$_id",
  135. 'name': '$name',
  136. 'collegecourse': '$relation_set.trainer_teaches_course_in_college',
  137. 'email_id': '$attribute_set.email_id',
  138. }
  139. },
  140. {
  141. '$sort': {'name': 1}
  142. }
  143. ])
  144. records_list = res["result"]
  145. colg_list_name = []
  146. if records_list:
  147. for each in res["result"]:
  148. if 'college' in each:
  149. if each['college']:
  150. if each["college"][0]:
  151. colg_list_name = []
  152. for each_col in each["college"][0]:
  153. colg_id = each_col
  154. colg_node = node_collection.one({'_id':ObjectId(colg_id)})
  155. colg_list_name.append(colg_node.name)
  156. each["college"] = colg_list_name
  157. colg_list_name = []
  158. str_colg_course = ""
  159. if 'collegecourse' in each:
  160. if each['collegecourse']:
  161. if each["collegecourse"][0]:
  162. # each["collegecourse"][0] is list of lists
  163. for eachcc in each["collegecourse"][0]:
  164. # eachcc is one list holding Course and College
  165. first = True
  166. for colg_course in eachcc:
  167. n = node_collection.one({'_id': ObjectId(colg_course)}).name
  168. str_colg_course += n
  169. if first:
  170. str_colg_course += " - "
  171. else:
  172. str_colg_course += "; "
  173. first = False
  174. # print "\n\nvt", eachcc
  175. # colg_list_name = eachcc
  176. each["college"] = str_colg_course
  177. ac_data_set.append(each)
  178. colg_list_name = []
  179. column_headers = [
  180. ("person_id", "Edit"),
  181. ("name", "Name"),
  182. ("email_id", "Email"),
  183. ("college", "College"),
  184. ]
  185. response_dict["column_headers"] = column_headers
  186. response_dict["success"] = True
  187. response_dict["students_data_set"] = ac_data_set
  188. response_dict["groupid"] = group_id
  189. response_dict["app_id"] = app_id
  190. response_dict["app_set_id"] = app_set_id
  191. template = "ndf/person_list.html"
  192. else:
  193. query = {}
  194. if request.method == "POST":
  195. search = request.POST.get("search","")
  196. query = {'member_of': person_gst._id, 'group_set': ObjectId(group_id), 'name': {'$regex': search, '$options': 'i'}}
  197. else:
  198. query = {'member_of': person_gst._id, 'group_set': ObjectId(group_id)}
  199. rec = node_collection.collection.aggregate([{'$match': query},
  200. {'$project': {'_id': 1,
  201. 'name': '$name',
  202. 'gender': '$attribute_set.gender',
  203. 'dob': '$attribute_set.dob',
  204. 'email_id': '$attribute_set.email_id',
  205. }},
  206. {'$sort': {'name': 1}}
  207. ])
  208. nodes = []
  209. if len(rec["result"]):
  210. for each_dict in rec["result"]:
  211. new_dict = {}
  212. for each_key in each_dict:
  213. if each_dict[each_key]:
  214. if type(each_dict[each_key]) == list:
  215. data = each_dict[each_key][0]
  216. else:
  217. data = each_dict[each_key]
  218. if type(data) == list:
  219. # Perform parsing
  220. if type(data) == list:
  221. # Perform parsing
  222. if type(data[0]) in [unicode, basestring, int]:
  223. new_dict[each_key] = ', '.join(str(d) for d in data)
  224. elif type(data[0]) in [ObjectId]:
  225. # new_dict[each_key] = str(data)
  226. d_list = []
  227. for oid in data:
  228. d = node_collection.one({'_id': oid}, {'name': 1})
  229. d_list.append(str(d.name))
  230. new_dict[each_key] = ', '.join(str(n) for n in d_list)
  231. elif type(data) == datetime.datetime:
  232. new_dict[each_key] = data.strftime("%d/%m/%Y")
  233. elif type(data) == long:
  234. new_dict[each_key] = str(data)
  235. elif type(data) == bool:
  236. if data:
  237. new_dict[each_key] = "Yes"
  238. else:
  239. new_dict[each_key] = "No"
  240. else:
  241. new_dict[each_key] = str(data)
  242. else:
  243. # Perform parsing
  244. if type(data) == list:
  245. # Perform parsing
  246. if type(data[0]) in [unicode, basestring, int]:
  247. new_dict[each_key] = ', '.join(str(d) for d in data)
  248. elif type(data[0]) in [ObjectId]:
  249. new_dict[each_key] = str(data)
  250. elif type(data) == datetime.datetime:
  251. new_dict[each_key] = data.strftime("%d/%m/%Y")
  252. elif type(data) == long:
  253. new_dict[each_key] = str(data)
  254. elif type(data) == bool:
  255. if data:
  256. new_dict[each_key] = "Yes"
  257. else:
  258. new_dict[each_key] = "No"
  259. else:
  260. new_dict[each_key] = str(data)
  261. else:
  262. new_dict[each_key] = ""
  263. nodes.append(new_dict)
  264. nodes_keys = [('name', "Name"),
  265. ('gender', "Gender"),
  266. ('dob', 'Birth Date'),
  267. ('email_id', 'Email ID')
  268. ]
  269. default_template = "ndf/mis_list.html"
  270. if app_set_instance_id:
  271. template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_details.html"
  272. default_template = "ndf/person_details.html"
  273. node = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
  274. property_order_list = get_property_order_with_value(node)
  275. node.get_neighbourhood(node.member_of)
  276. context_variables = { 'groupid': group_id,
  277. 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set,
  278. 'app_set_id': app_set_id,
  279. 'title':title,
  280. 'nodes': nodes, "nodes_keys": nodes_keys, 'node': node,
  281. 'property_order_list': property_order_list, 'lstFilters': widget_for,
  282. 'univ_list':json.dumps(univ_list, cls=NodeJSONEncoder),
  283. 'is_link_needed': is_link_needed,
  284. 'response_dict':json.dumps(response_dict, cls=NodeJSONEncoder)
  285. }
  286. try:
  287. return render_to_response([template, default_template],
  288. context_variables,
  289. context_instance = RequestContext(request)
  290. )
  291. except TemplateDoesNotExist as tde:
  292. error_message = "\n PersonDetailListViewError: This html template (" + str(tde) + ") does not exists !!!\n"
  293. raise Http404(error_message)
  294. except Exception as e:
  295. error_message = "\n PersonDetailListViewError: " + str(e) + " !!!\n"
  296. raise Exception(error_message)
  297. @login_required
  298. @get_execution_time
  299. def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None):
  300. """
  301. Creates/Modifies document of given person-type.
  302. """
  303. auth = None
  304. if ObjectId.is_valid(group_id) is False :
  305. group_ins = node_collection.one({'_type': "Group", "name": group_id})
  306. auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  307. if group_ins:
  308. group_id = str(group_ins._id)
  309. else :
  310. auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  311. if auth :
  312. group_id = str(auth._id)
  313. else :
  314. pass
  315. app = None
  316. if app_id is None:
  317. app = node_collection.one({'_type': "GSystemType", 'name': app_name})
  318. if app:
  319. app_id = str(app._id)
  320. else:
  321. app = node_collection.one({'_id': ObjectId(app_id)})
  322. app_name = app.name
  323. # app_name = "mis"
  324. app_set = ""
  325. app_collection_set = []
  326. title = ""
  327. person_gst = None
  328. person_gs = None
  329. college_node = None
  330. college_id = None
  331. student_enrollment_code = u""
  332. create_student_enrollment_code = False
  333. existing_colg = []
  334. registration_date = None
  335. property_order_list = []
  336. template = ""
  337. template_prefix = "mis"
  338. if request.user:
  339. if auth is None:
  340. auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
  341. agency_type = auth.agency_type
  342. agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
  343. if agency_type_node:
  344. for eachset in agency_type_node.collection_set:
  345. app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  346. # for eachset in app.collection_set:
  347. # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  348. college_node = node_collection.one({
  349. "_id": ObjectId(group_id),
  350. "relation_set.group_of": {"$exists": True}
  351. }, {
  352. "relation_set.group_of": 1
  353. })
  354. if app_set_id:
  355. person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
  356. template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_create_edit.html"
  357. title = person_gst.name
  358. person_gs = node_collection.collection.GSystem()
  359. person_gs.member_of.append(person_gst._id)
  360. if app_set_instance_id:
  361. person_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
  362. property_order_list = get_property_order_with_value(person_gs)#.property_order
  363. if request.method == "POST":
  364. if person_gst.name == "Student" and "_id" not in person_gs:
  365. create_student_enrollment_code = True
  366. # [A] Save person-node's base-field(s)
  367. is_changed = get_node_common_fields(request, person_gs, group_id, person_gst)
  368. if is_changed:
  369. # Remove this when publish button is setup on interface
  370. person_gs.status = u"PUBLISHED"
  371. person_gs.save(is_changed=is_changed,groupid=group_id)
  372. for each_rel in person_gs.relation_set:
  373. if each_rel and "officer_incharge_of" in each_rel:
  374. existing_colg = each_rel["officer_incharge_of"]
  375. if college_node:
  376. mis_admin = node_collection.one({
  377. "_type": "Group",
  378. "name": "MIS_admin"
  379. }, {
  380. "_id": 1
  381. }
  382. )
  383. node_collection.collection.update({
  384. "_id": person_gs._id
  385. }, {
  386. "$addToSet": {"group_set": mis_admin._id}
  387. },
  388. upsert=False, multi=False
  389. )
  390. # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs)
  391. for tab_details in property_order_list:
  392. for field_set in tab_details[1]:
  393. # Fetch only Attribute field(s) / Relation field(s)
  394. if '_id' in field_set:
  395. field_instance = node_collection.one({'_id': field_set['_id']})
  396. fi_name = field_instance["name"]
  397. field_instance_type = type(field_instance)
  398. if field_instance_type in [AttributeType, RelationType]:
  399. field_data_type = field_set['data_type']
  400. # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
  401. if field_instance_type == AttributeType:
  402. if "File" in field_instance["validators"]:
  403. # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
  404. user_id = request.user.id
  405. if fi_name in request.FILES:
  406. field_value = request.FILES[fi_name]
  407. else:
  408. field_value = ""
  409. # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
  410. if field_value != '' and field_value != u'':
  411. file_name = person_gs.name + " -- " + field_instance["altnames"]
  412. content_org = ""
  413. tags = ""
  414. 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]
  415. else:
  416. # Other AttributeTypes
  417. if fi_name in request.POST:
  418. field_value = request.POST[fi_name]
  419. # field_instance_type = "GAttribute"
  420. if fi_name in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
  421. field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
  422. elif fi_name in ["dob", "registration_date"]:
  423. field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
  424. registration_date = field_value
  425. else:
  426. field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")
  427. if field_value:
  428. person_gs_triple_instance = create_gattribute(person_gs._id, node_collection.collection.AttributeType(field_instance), field_value)
  429. else:
  430. if field_instance["object_cardinality"] > 1:
  431. field_value_list = request.POST.get(fi_name, "")
  432. if "[" in field_value_list and "]" in field_value_list:
  433. field_value_list = json.loads(field_value_list)
  434. else:
  435. field_value_list = request.POST.getlist(fi_name)
  436. else:
  437. field_value_list = request.POST.getlist(fi_name)
  438. if META_TYPE[3] in field_instance.member_of_names_list:
  439. # If Binary relationship found
  440. # [id, id, ...]
  441. # field_instance_type = "GRelation"
  442. for i, field_value in enumerate(field_value_list):
  443. field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
  444. field_value_list[i] = field_value
  445. else:
  446. # Relationship Other than Binary one found; e.g, Triadic
  447. # [[id, id, ...], [id, id, ...], ...]
  448. # field_instance_type = "GRelation"
  449. for i, field_value_inner_list in enumerate(field_value_list):
  450. for j, field_value in enumerate(field_value_inner_list):
  451. field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
  452. field_value_list[i][j] = field_value
  453. person_gs_triple_instance = create_grelation(person_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)
  454. # Setting enrollment code for student node only while creating it
  455. if create_student_enrollment_code:
  456. # Create enrollment code for student node only while registering a new node
  457. for rel in college_node.relation_set:
  458. if rel and "group_of" in rel:
  459. college_id = rel["group_of"][0]
  460. student_enrollment_code = get_student_enrollment_code(college_id, person_gs._id, registration_date, ObjectId(group_id))
  461. enrollment_code_at = node_collection.one({
  462. "_type": "AttributeType", "name": "enrollment_code"
  463. })
  464. try:
  465. ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code)
  466. except Exception as e:
  467. print "\n StudentEnrollmentCreateError: " + str(e) + "!!!"
  468. # [C] Code to link GSystem Node and Author node via "has_login" relationship;
  469. # and Subscribe the Author node to College group if user "Program Officer"
  470. person_gs.reload()
  471. auth_node = None
  472. for attr in person_gs.attribute_set:
  473. if "email_id" in attr:
  474. if attr["email_id"]:
  475. auth_node = node_collection.one({'_type': "Author", 'email': attr["email_id"].lower()})
  476. break
  477. if auth_node:
  478. has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"})
  479. if has_login_rt:
  480. # Linking GSystem Node and Author node via "has_login" relationship;
  481. gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id)
  482. # Set author_agency field's value of author node as "Program Officer"
  483. # Required to identify at time of log-in in order to display
  484. # required modules defined for Program Officers under MIS GApp
  485. if auth_node.agency_type != u"Program Officer":
  486. auth_node.agency_type = u"Program Officer"
  487. auth_node.save(groupid=group_id)
  488. if "Program Officer" in person_gs.member_of_names_list:
  489. # If Person node (GSystem) is of Program Officer type
  490. # then only go for subscription
  491. college_id_list = []
  492. # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of")
  493. for rel in person_gs.relation_set:
  494. if "officer_incharge_of" in rel:
  495. if rel["officer_incharge_of"]:
  496. for college_id in rel["officer_incharge_of"]:
  497. if college_id not in college_id_list:
  498. college_id_list.append(college_id)
  499. break # break outer-loop (of relation_set)
  500. if college_id_list:
  501. # If College's ObjectId exists (list as PO might be assigned to more than one college)
  502. # Then prepare a list of their corresponding private group(s) (via "has_group")
  503. college_cur = node_collection.find(
  504. {'_id': {'$in': college_id_list}},
  505. {'relation_set.has_group': 1}
  506. )
  507. college_group_id_list = []
  508. for college in college_cur:
  509. for rel in college.relation_set:
  510. if rel and "has_group" in rel:
  511. if rel["has_group"]:
  512. if rel["has_group"][0] not in college_group_id_list:
  513. college_group_id_list.append(rel["has_group"][0])
  514. break # break inner-loop (college.relation_set)
  515. if college_group_id_list:
  516. # If college-group list exists
  517. # Then update their group_admin field (append PO's created_by)
  518. res = node_collection.collection.update(
  519. {'_id': {'$in': college_group_id_list}},
  520. {'$addToSet': {'group_admin': auth_node.created_by}},
  521. upsert=False, multi=True
  522. )
  523. old_college_id_list = []
  524. if existing_colg:
  525. if len(existing_colg) > len(college_id_list):
  526. for each_colg_id in existing_colg:
  527. if each_colg_id not in college_id_list:
  528. old_college_id_list.append(each_colg_id)
  529. old_college_cur = node_collection.find(
  530. {'_id': {'$in': old_college_id_list}},
  531. {'relation_set.has_group': 1}
  532. )
  533. old_college_group_id_list = []
  534. for college in old_college_cur:
  535. for rel in college.relation_set:
  536. if rel and "has_group" in rel:
  537. if rel["has_group"]:
  538. if rel["has_group"][0] not in old_college_group_id_list:
  539. old_college_group_id_list.append(rel["has_group"][0])
  540. break # break inner-loop (college.relation_set)
  541. if old_college_group_id_list:
  542. # If college-group list exists
  543. # Then update their group_admin field (remove PO's created_by)
  544. res = node_collection.collection.update(
  545. {'_id': {'$in': old_college_group_id_list}, '$or': [{'group_admin': auth_node.created_by},
  546. {'author_set': auth_node.created_by}]},
  547. {'$pull': {'group_admin': auth_node.created_by, 'author_set': auth_node.created_by}},
  548. upsert=False, multi=True
  549. )
  550. # The code below is commented as the college groups are PRIVATE.
  551. # for rel in person_gs.relation_set:
  552. # if rel and "officer_incharge_of" in rel:
  553. # pass
  554. # else:
  555. # node_collection.collection.update({'_id': auth_node._id},
  556. # {'$set': {'agency_type': u"Other"}},
  557. # upsert=False, multi=False
  558. # )
  559. # Its purpose is to change the agency type back to Other
  560. auth_node.reload()
  561. # if person_gst.name != "Student":
  562. # 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}))
  563. # else:
  564. 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)}))
  565. # 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}))
  566. default_template = "ndf/person_create_edit.html"
  567. # default_template = "ndf/"+template_prefix+"_create_edit.html"
  568. context_variables = { 'groupid': group_id, 'group_id': group_id,
  569. 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set,
  570. 'app_set_id': app_set_id,
  571. 'title':title,
  572. 'property_order_list': property_order_list
  573. }
  574. if person_gst and person_gst.name in ["Voluntary Teacher", "Master Trainer"]:
  575. 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})
  576. if nussd_course_type["data_type"] == "IS()":
  577. # Below code does little formatting, for example:
  578. # data_type: "IS()" complex_value: [u"ab", u"cd"] dt:
  579. # "IS(u'ab', u'cd')"
  580. dt = "IS("
  581. for v in nussd_course_type.complex_data_type:
  582. dt = dt + "u'" + v + "'" + ", "
  583. dt = dt[:(dt.rfind(", "))] + ")"
  584. nussd_course_type["data_type"] = dt
  585. nussd_course_type["data_type"] = eval(nussd_course_type["data_type"])
  586. nussd_course_type["value"] = None
  587. context_variables['nussd_course_type'] = nussd_course_type
  588. if app_set_instance_id:
  589. person_gs.get_neighbourhood(person_gs.member_of)
  590. if "trainer_teaches_course_in_college" in person_gs:
  591. l = []
  592. for each_course_college in person_gs.trainer_teaches_course_in_college:
  593. # Fetch Course Type (i.e. nussd_course_type)
  594. ct = ""
  595. for each_attr in each_course_college[0].attribute_set:
  596. if "nussd_course_type" in each_attr and each_attr:
  597. ct = each_attr["nussd_course_type"]
  598. break
  599. univ_name = ""
  600. for each_rel in each_course_college[1].relation_set:
  601. if "college_affiliated_to" in each_rel and each_rel:
  602. univ = node_collection.find_one({"_id": {"$in": each_rel["college_affiliated_to"]}})
  603. univ_name = univ.name if univ else ""
  604. l.append((
  605. ct, each_course_college[0].name, each_course_college[1].name,
  606. each_course_college[0]._id.__str__(),
  607. each_course_college[1]._id.__str__(),
  608. univ_name
  609. ))
  610. if l:
  611. person_gs.trainer_teaches_course_in_college = l
  612. context_variables['node'] = person_gs
  613. try:
  614. return render_to_response([template, default_template],
  615. context_variables,
  616. context_instance = RequestContext(request)
  617. )
  618. except TemplateDoesNotExist as tde:
  619. error_message = "\n PersonCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n"
  620. raise Http404(error_message)
  621. except Exception as e:
  622. error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n"
  623. raise Exception(error_message)