def get_context_data(self, **kwargs): """Extension of get_context_data Add context data to drive detail view. """ context = super(TemplateDetailView, self).get_context_data(**kwargs) context['selected_scenario'] = self.request.session['selected_scenario'] adapter = EMOD_Adapter() my_template_id = kwargs['template_id'] my_temp_list = adapter.fetch_template_list() for id in my_temp_list: if id == int(my_template_id): context['template_name'] = my_temp_list[id]['name'] context['template_description'] = my_temp_list[id]['description'] context['template_campaign_description'] = my_temp_list[id]['files']['campaign.json']['description'] context['template_config_description'] = my_temp_list[id]['files']['config.json']['description'] my_loc_list = adapter.fetch_locations() for loc_id in my_loc_list: if loc_id == my_temp_list[id]['location_ndx']: context['template_location_name'] = my_loc_list[loc_id]['place'] + ', ' + my_loc_list[loc_id]['country'] context['template_location_start_date'] = my_loc_list[loc_id]['start_date'] context['template_location_end_date'] = my_loc_list[loc_id]['end_date'] context['template_location_resolution'] = my_loc_list[loc_id]['resolution'] context['template_location_link'] = my_loc_list[loc_id]['link'] my_temp = adapter.fetch_template(int(kwargs['template_id'])) my_config = ast.literal_eval(my_temp['config.json']) context['template_campaign_warning'] = my_config['parameters']['Enable_Interventions'] context['template_config'] = re.sub("\r{2,}", '\r', my_temp['config.json']) context['template_campaign'] = re.sub("\r{2,}", '\r', my_temp['campaign.json']) return context
def get_context_data(self, form, **kwargs): """Extension of the get_context_data method of the NamedUrlSessionWizardView. Select/process data based on which step of the Form Wizard it's called for. - Date: passes existing start_date, end_date values or nothing then template will use min and max. - Preview gets all wizard step data gathered so far. """ context = super(BaselineWizardView, self).get_context_data(form=form, **kwargs) # All steps: if 'edit_scenario' in self.storage.extra_data: # if we're in edit mode, let templates know ("Start Over" vs "Cancel Edit" button) context['edit_scenario'] = self.storage.extra_data['edit_scenario'] ######### Start code for specific steps ######### if self.steps.current == 'location': the_request = self.request adapter = EMOD_Adapter(self.request.user.username) templates = adapter.fetch_template_list() # get for description for key in templates.keys(): if 'edit_scenario' in self.storage.extra_data \ and 'scenario' in self.request.session.keys() \ and self.request.session['scenario'].template is not None \ and self.request.session['scenario'].template.id is not None \ and self.request.session['scenario'].template.id == key: # set the checked option based on the scenario being edited templates[key]['checked'] = 1 elif 'location' in self.storage.data['step_data'].keys()\ and 'location-template_id' in self.storage.data['step_data'][u'location'].keys()\ and unicode(key) == \ self.storage.data['step_data'][u'location'][u'location-template_id'][0]: # set checked option based on wizard value already saved templates[key]['checked'] = 1 # For now: limit list to Solomon and Kenya templates templates_a = {} templates_b = {} templates_c = {} templates_d = {} templates_e = {} # reorder the templates so Vietnam 1st, Kenya 2nd, Solomon 3rd for key in templates.keys(): if 'Vietnam' in templates[key]['name']: templates_a.update({key: templates[key]}) for key in templates.keys(): if 'Kenya' in templates[key]['name']: templates_b.update({key: templates[key]}) for key in templates.keys(): if 'Solomon' in templates[key]['name']: templates_c.update({key: templates[key]}) for key in templates.keys(): if 'Uganda' in templates[key]['name']: templates_d.update({key: templates[key]}) for key in templates.keys(): if 'Bougainville' in templates[key]['name']: templates_e.update({key: templates[key]}) pager_size = the_request.POST.get('pager_size') if pager_size is None: pager_size = 10 else: pager_size = int(pager_size) pager_offset = the_request.POST.get('pager_offset') if pager_offset is None: pager_offset = 0 else: pager_offset = int(pager_offset) pager_group = the_request.POST.get('pager_group') if pager_group is None: pager_group = 0 else: try: pager_group = int(pager_group) except TypeError: pager_group = 0 template_count = len(templates) pager_count = template_count / pager_size if template_count % pager_size != 0: pager_count += 1 context['pager_offset'] = pager_offset context['pager_size'] = pager_size context['pager_group'] = pager_group context['pager_count'] = range(1, pager_count + 1) context['pager_max'] = pager_count context['templates_a'] = templates_a context['templates_b'] = templates_b context['templates_c'] = templates_c context['templates_d'] = templates_d context['templates_e'] = templates_e context['template_count'] = template_count context['current_start'] = pager_offset * pager_size + 1 context['current_stop'] = min(template_count, pager_offset * pager_size + pager_size) return context if self.steps.current == 'climate': my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id']) context['template'] = my_template # set up the context to include the files (if any) attached to the scenario my_types = [ 'air binary', #'air json', 'humidity binary', #'humidity json', #'land_temp binary', #'land_temp json', 'rainfall binary'] #'rainfall json'] # get scenario files: types/names context['climate_files'] = {} for my_file in self.request.session['scenario'].get_files(): # my_file[0] id # my_file[1] name # my_file[2] type if my_file[2] in my_types: context['climate_files'].update({my_file[2].split(' ')[0]: my_file[1]}) context['climate_files'] = sorted(context['climate_files'].iteritems()) context['scenario_id'] = self.request.session['scenario'].id my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id']) context['template'] = my_template if self.steps.current == 'demographic': my_template = DimTemplate.objects.get(id=self.storage.extra_data['template_id']) context['template'] = my_template if self.steps.current == 'species': ### # Get list of species user can base NEW species creation on (drop-down menu) # and to use for adding to a simulation # get from template try: context['species_templates'] = \ self.storage.extra_data['scenario_template_config']['parameters']['Vector_Species_Params'] except KeyError: pass ### # Modify the above list to make the "select from" sources species_list = [] try: # turn into objects for key, value in context['species_templates'].items(): json_string = '{"' + key + '":' + json.dumps(value) + "}" species_list.append(Species(name=key, is_template=1, is_public=0, json=json_string, created_by=self.request.user)) except KeyError: pass # Add in public and user's own custom species objects from DB for species in Species.objects.filter(Q(is_public=1) | Q(created_by=self.request.user)): species_list.append(species) # This serves as the "from template", "user's custom" and "public" species available context['species_list'] = species_list ### # Populate the already chosen list # # Get Baseline or Template ID for passing to SpeciesCreate View # # because wizard storage won't be available in SpeciesCreate View my_scenario_id = self.storage.extra_data.get('scenario_id') my_species = [] try: my_species.extend(self.request.session['scenario_config']['parameters']['Vector_Species_Names']) except (KeyError, TypeError): pass my_species = sorted(set(my_species)) context['species_chosen'] = {u'species-species': json.dumps(my_species), 'scenario_id': my_scenario_id, u'orig_json_obj': ConfigData.objects.filter( type='JSONConfig', name='default_emod_vector')[0].json} context['species_chosen_values'] = \ json.dumps(self.request.session['scenario_config']['parameters']['Vector_Species_Params']) if self.steps.current == 'parasite' or self.steps.current == "vector": step_name = self.steps.current # build titles for template from name, misc my_object = ConfigData.objects.filter(type='JSONConfig', name=step_name)[0] context['step_title'] = step_name.title() + " " + my_object.misc.split(":")[1].title() context['description'] = my_object.description # if the user has not already been through this step # populate the form with the template values. if not self.storage.get_step_data(step_name): try: context['template_values'] = self.request.session['scenario_config']['parameters'] except KeyError: pass if self.steps.current == 'run': form.fields['name'].initial = 'Test Run ' + str(datetime.datetime.now()) if self.steps.current == 'review': # get list of runs for this scenario adapter = EMOD_Adapter(self.request.user.username) run_list = DimRun.objects.filter(baseline_key=self.request.session['scenario'].id) if len(run_list) > 0: # sort descending by id (for those old runs that all have the same old time_created run_list = sorted(run_list, key=lambda x: x.id, reverse=True) # sort descending by time_saved run_list = sorted(run_list, key=lambda x: x.time_created, reverse=True) # get most recent run, is it still running? my_run = run_list[0] # check to see if a run is currently running status = adapter.run_status(my_run.id) if status is None: my_run.my_completed = None else: my_run.my_completed = status[0] my_run.my_failed = status[2] if status[0] > 0: context['scenario_has_results'] = 1 # this sets if any of the runs here has results my_run.my_total = status[1] my_run.my_percent_complete = float(status[0]) / float(status[1]) * 100 my_run.my_percent_failed = float(status[2]) / float(status[1]) * 100 my_run.errors = adapter.fetch_errors(my_run.id) # get the results for the last run(s) if it's finished context['my_run'] = my_run # #6329 - pass in scenario for display of info context['scenario'] = self.request.session['scenario'] my_config = self.request.session['scenario'].get_file_by_type('config').content context['Simulation_Duration'] = ast.literal_eval(my_config)['parameters']['Simulation_Duration'] if self.steps.current == 'run': # check for existing runs in this scenario if 'scenario' in self.request.session.keys(): my_runs = DimRun.objects.filter(baseline_key=self.request.session['scenario'].id) if len(my_runs) > 0: context['has_runs'] = len(my_runs) # populate the step data so if the skip button is used, # the wizard doesn't skip back to here upon wizard submission (skip isn't a submit, just goto_step) self.storage.set_step_data('run', {u'baseline_wizard_view-current_step': [u'run']}) return context
def get_context_data(self, **kwargs): """Extension of get_context_data Add context data to drive menu nav highlights, breadcrumbs and pagers. """ context = super(ScenarioBrowseView, self).get_context_data(**kwargs) the_request = self.request context['nav_button'] = 'scenario_browse' pager_size = the_request.POST.get('pager_size') or the_request.GET.get('pager_size') if pager_size is None: pager_size = 10 else: pager_size = int(pager_size) # Get list of folders in this folder (if no current folder, include folders with no parent) if 'folder_id' in kwargs.keys(): current_folder = kwargs['folder_id'] or the_request.POST.get('folder_id') or the_request.GET.get('folder_id') or None context['current_folder'] = Folder.objects.get(pk=current_folder) else: current_folder = None # get a list of all scenarios in order to get count of sims in each folder scenario_list_all = list(DimBaseline.objects.filter(user=DimUser.objects.get(username=self.request.user.username), is_deleted=False)) my_count = {} for scen in scenario_list_all: if scen.folder_id in my_count.keys(): my_count[scen.folder_id] += 1 else: my_count[scen.folder_id] = 1 # create a dictionary of children (keys are parents, value is list of children) folder_list_all = list(Folder.objects.filter(user=DimUser.objects.get(username=self.request.user.username), is_deleted=False)) my_dict = defaultdict(list) for folder in folder_list_all: if folder.id in my_count.keys(): counter = ' (' + str(my_count[folder.id]) + ')' else: counter = '' if folder.parent is None: my_dict[0].append({'id': folder.id, 'name': folder.name, 'child_count': counter}) else: my_dict[folder.parent.id].append({'id': folder.id, 'name': folder.name, 'child_count': counter}) current_found = 0 # Set flag that deterimines if the current folder has been visited in the tree if None in my_count.keys(): counter_root = ' (' + str(my_count[None]) + ')' else: counter_root = '' folder_tree = '{title: "My Simulations' + counter_root + '", folder: true, expanded: true' if current_folder is None: folder_tree += ', active: true' current_found = 1 # context['folder_tree'] = '{title: "My Tororo Folder full of Simulations (and folders) in home folder ", folder: true }, ' \ # '{title: "Folder 2", folder: true, ' \ # 'children: [ ' \ # '{ title: "Sub-item 2.1", folder: true }, ' \ # '{ title: "Sub-item 2.2" }] }, ' \ # '{ title: "Item 3" }' # without root: # context['folder_tree'] = '{title: "Solomon Islands", folder: true}, {title: "Second folder", folder: true, children: [ {title: "subfolder", folder: true}] }' #folder_tree = add_children(0, my_dict) # with root: # context['folder_tree'] = '{title: "My Simulations", folder: true, children: [ {title: "Solomon Islands", folder: true}, {title: "Second folder", folder: true, children: [ {title: "subfolder", folder: true}] }] }' folder_tree += add_children(0, my_dict, current_folder, current_found) + '}' context['folder_tree'] = str(folder_tree) # Get list of scenarios scenario_list = list(DimBaseline.objects.filter(user=DimUser.objects.get(username=self.request.user.username), folder=current_folder, is_deleted=False)) if scenario_list is None: return context # sort descending by id (for those old scenarios that all have the same old time_created scenario_list = sorted(scenario_list, key=lambda x: x.id, reverse=True) # sort descending by time_saved (version) scenario_list = sorted(scenario_list, key=lambda x: x.last_modified, reverse=True) # merge folders into scenario list # - show folders in file list #scenario_list = folder_list + scenario_list # Flag scenarios that are representative for scenario in scenario_list: # Hack for now. I don't remember if it is still needed, but I will fix it later. Not currently important. if scenario.description == "Made with representative workflow" and not scenario.metadata: scenario.metadata = json.dumps({'representative': ''}) scenario.save() if scenario.metadata: metadata = json.loads(scenario.metadata) if 'representative' in metadata: scenario.is_representative = True if 'is_complete' in metadata['representative']: scenario.representative_is_complete = metadata['representative']['is_complete'] else: scenario.representative_is_complete = False scenario.name = derive_autoname(scenario) else: scenario.is_representative = False paginator = Paginator(scenario_list, pager_size) page = int(the_request.GET.get('page') or 1) try: scenarios = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. scenarios = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. scenarios = paginator.page(paginator.num_pages) scenario_count = len(scenario_list) context['pager_size'] = pager_size context['scenarios'] = scenarios context['scenario_range'] = range(paginator.num_pages) context['scenario_count'] = scenario_count context['current_start'] = (page-1)*pager_size + 1 context['current_stop'] = min(scenario_count, (page-1)*pager_size + pager_size) context['my_username'] = self.request.user.username # get locations (need name from dict by id) adapter = EMOD_Adapter(self.request.user.username) template_list = adapter.fetch_template_list() location_dict = adapter.fetch_locations() # gets list based on EMOD_buffer list in model_adapter.py # determine which step edit buttons link to step_list = [i[0] for i in named_baseline_forms] for scenario in scenario_list: if scenario._meta.object_name != 'Folder': try: # check to see if it has a campaign file (besides the empty default) if scenario.is_approved: my_scenario = EMODBaseline.from_dw(pk=scenario['id']) try: scenario_campaign = json.dumps(ast.literal_eval(my_scenario.get_file_by_type('campaign').content), sort_keys=True, indent=4, separators=(',', ': ')) except (AttributeError, ObjectDoesNotExist): try: # if file list was returned, use last file scenario_campaign = json.dumps(ast.literal_eval( my_scenario.get_file_by_type('campaign')[my_scenario.get_file_by_type('campaign').count() - 1].content), sort_keys=True, indent=4, separators=(',', ': ')) except ObjectDoesNotExist: pass if len(json.loads(scenario_campaign)['Events']) > 0: scenario['has_interventions'] = 1 if scenario.template: scenario.location_name = str(DimTemplate.objects.get(id=scenario.template.id).location_key) # add model version to scenario scenario.model_version = DimTemplate.objects.get(id=scenario.template.id)\ .model_version.replace('emod ', '') except: pass return context
def get_context_data(self, form, **kwargs): """Extension of the get_context_data method of the NamedUrlSessionWizardView. Select/process data based on which step of the Form Wizard it's called for. - Date: passes existing start_date, end_date values or nothing then template will use min and max. - Preview gets all wizard step data gathered so far. """ context = super(ScenarioCreateByTemplate, self).get_context_data(form=form, **kwargs) context["nav_button"] = "ts_ScenarioCreateByTemplate_step" # set flag to activate nav menu highlighting ######### Start code for specific steps ######### if self.steps.current == "location": the_request = self.request adapter = EMOD_Adapter(self.request.user.username) templates = adapter.fetch_template_list() # get for description if "folder_id" in kwargs.keys(): context["current_folder"] = kwargs["folder_id"] # For now: limit list to Solomon and Kenya templates templates_a = {} templates_b = {} templates_c = {} templates_d = {} templates_e = {} templates_garki = {} templates_new = {} # reorder the templates so Vietnam 1st, Kenya 2nd, Solomon 3rd for key in templates.keys(): if "Vietnam" in templates[key]["name"]: templates_a.update({key: templates[key]}) for key in templates.keys(): if "Kenya" in templates[key]["name"]: templates_b.update({key: templates[key]}) for key in templates.keys(): if "Solomon" in templates[key]["name"]: templates_c.update({key: templates[key]}) for key in templates.keys(): if "Uganda" in templates[key]["name"]: templates_d.update({key: templates[key]}) for key in templates.keys(): if "Bougainville" in templates[key]["name"]: templates_e.update({key: templates[key]}) for key in templates.keys(): if "New Location" in templates[key]["name"]: templates_new.update({key: templates[key]}) for key in templates.keys(): if "Garki" in templates[key]["name"]: templates_garki.update({key: templates[key]}) pager_size = the_request.POST.get("pager_size") if pager_size is None: pager_size = 10 else: pager_size = int(pager_size) pager_offset = the_request.POST.get("pager_offset") if pager_offset is None: pager_offset = 0 else: pager_offset = int(pager_offset) pager_group = the_request.POST.get("pager_group") if pager_group is None: pager_group = 0 else: try: pager_group = int(pager_group) except TypeError: pager_group = 0 # scenario_count = scenarios.count() template_count = len(templates) pager_count = template_count / pager_size if template_count % pager_size != 0: pager_count += 1 context["pager_offset"] = pager_offset context["pager_size"] = pager_size context["pager_group"] = pager_group context["pager_count"] = range(1, pager_count + 1) context["pager_max"] = pager_count context["templates_a"] = templates_a context["templates_b"] = templates_b context["templates_c"] = templates_c context["templates_d"] = templates_d context["templates_e"] = templates_e context["templates_new"] = templates_new context["templates_garki"] = templates_garki context["template_count"] = template_count context["current_start"] = pager_offset * pager_size + 1 context["current_stop"] = min(template_count, pager_offset * pager_size + pager_size) return context return context