def post(self, request): try: self.create_or_update_emod_snippet(request) except Exception as exception: set_notification('alert-error', '<strong>Error!</strong> The entry may not have been saved! ' + str(exception), self.request.session) return HttpResponseRedirect(reverse('ts_repr.manage_emod_snippet'))
def get_context_data(self, form, **kwargs): context = super(LaunchTool, self).get_context_data(form, **kwargs) try: context['nav_button'] = self.request.session['emod_nav_button'] except KeyError: pass # We need either a run id or scenario id (both really) if 'run_id' in kwargs: run_id = kwargs['run_id'] if run_id > 0: self.storage.extra_data['emod_launch_run_id'] = run_id context['run_named'] = 1 # get the run's name, to prepopulate the name field adapter = EMOD_Adapter(self.request.user.username) my_run_id = int(self.storage.extra_data['emod_launch_run_id']) my_run = adapter.fetch_runs(scenario_id=-1, run_id=int(my_run_id)) context['form'].fields['name'].initial = my_run.name # save for checking for changes in done method self.storage.extra_data['old_run_name'] = my_run.name #else: # get the specified scenario - error if none specified try: if 'scenario_id' in kwargs: self.storage.extra_data['scenario_id'] = kwargs['scenario_id'] elif 'scenario_id' not in self.storage.extra_data: self.storage.extra_data['error_invalid_id'] = 1 Exception() except KeyError: #If there was no scenario id in the url or storage, this wizard is useless... redirect somewhere else set_notification('alert-error', 'Error Launching Simulation: Unknown/Invalid run provided. ' + 'Please select a simulation below to launch.', self.request.session) return context
def create_or_update_emod_snippet(self, request): # Information for the standard attributes. If a emod_snippet_id of 0 is specified, a new # EMODSnippet entry will be made using these values. If an already existing id is specified, # the current values will stay and these values will be ignored. However, if the id is not 0 and is not an # already existent entry, this will overwrite the current values with these values. emod_snippet_id = int(request.POST['emod_snippet_id']) name = request.POST['name'] description = request.POST['description'] snippet = request.POST['emod_snippet'] # 0 means we are explicitly requesting a new object, else we are looking for a specific one that supposedly # already exists, but if it doesn't, it will be created anyway if emod_snippet_id == 0: emod_snippet = EMODSnippet(name=name, description=description, snippet=snippet) else: try: # Does exist, so use current values emod_snippet = EMODSnippet.objects.get(id=emod_snippet_id) emod_snippet.name = name emod_snippet.description = description emod_snippet.snippet = snippet except: # Doesn't exist, so fill in with values from above emod_snippet = EMODSnippet(name=name, description=description, snippet=snippet) emod_snippet.save() if 'Sporozoite_Rate' in json.loads(snippet)[name]: set_notification('alert-success', '<strong>Success!</strong> Successfully saved.', self.request.session) else: set_notification('alert-error', '<strong>Success with warning!</strong> Successfully saved, however Sporozoite_Rate was not added!', self.request.session)
def get_context_data(self, **kwargs): """Extension of get_context_data populate the existing metaData values """ context = super(RunMetadataDetailView, self).get_context_data(**kwargs) the_request = self.request adapter = EMOD_Adapter(the_request.user.username) my_run = adapter.fetch_runs(run_id=int(kwargs['run_id'])) # if we got here by edit URL, set edit mode. if 'mode' in kwargs.keys() and kwargs['mode'] == 'edit' and my_run.baseline_key.user.username == the_request.user.username: context['edit'] = True try: context['metaData'] = RunMetaData(my_run) except RuntimeError: set_notification('alert-error', '<strong>Error!</strong> Failed to retrieve metadata.', self.request.session) scenario_id = my_run.baseline_key if scenario_id: return redirect("ts_emod_scenario_details", scenario_id=str(scenario_id)) else: return redirect("ts.index") return context
def launch_scenario(request, scenario_id): dim_user = DimUser.objects.get(username=request.user.username) scenario = Scenario.objects.get(id=scenario_id) config_json = json.loads(scenario.config_file.get_contents()) print config_json['parameters']['Land_Temperature_Filename'] print config_json['parameters']['Rainfall_Filename'] print config_json['parameters']['Relative_Humidity_Filename'] print config_json['parameters']['Air_Temperature_Filename'] print config_json['parameters']['Campaign_Filename'] print config_json['parameters']['Demographics_Filename'] # config_json['parameters']['Land_Temperature_Filename'] = 'temperature.bin' # config_json['parameters']['Rainfall_Filename'] = 'rainfall.bin' # config_json['parameters']['Relative_Humidity_Filename'] = 'humidity.bin' # config_json['parameters']['Air_Temperature_Filename'] = 'temperature.bin' # config_json['parameters']['Campaign_Filename'] = 'campaign.json' # config_json['parameters']['Demographics_Filename'] = 'demographics.compiled.json' config_json['parameters']['Simulation_Duration'] = 100 try: scenario.set_file_by_type('config', json.dumps(config_json)) except RuntimeError as error: set_notification('alert-error', '<strong>Error!</strong> ' + str(error), request.session) return redirect("ts_emod2.details", scenario_id=scenario_id) submit(request, sim_model.EMOD, scenario_id) set_notification('alert-success', '<strong>Success!</strong> Job submitted.', request.session) return redirect("ts_emod2.details", scenario_id=scenario_id)
def deleteIntervention(request, intervention_id): try: Intervention_to_delete = Intervention.objects.get(id=intervention_id, created_by=request.user.id) Intervention_to_delete.delete() set_notification('alert-success', '<strong>Success!</strong> You have successfully deleted the Intervention.', request.session) except: print 'Error deleting Intervention with id: %s' % intervention_id set_notification('alert-error', '<strong>ERROR:</strong> There was a problem that prevented ' 'the deletion of the Intervention.', request.session)
def deleteNote(request, note_id): """Function to delete Species DB Objects """ try: note_to_delete = Note.objects.get(id=note_id) note_to_delete.delete() set_notification('alert-success','<strong>Success!</strong> You have successfully deleted the note.', request.session) except: print 'Error deleting note with id: %s' % note_id set_notification('alert-error','<strong>Error!</strong> There was a problem deleting the note.', request.session) return redirect('ts_emod_run_browse')
def submit_a_verification_job(request, scenario_id): adapter = EMOD_Adapter(request.user.username) emod_scenario = EMODBaseline.from_dw(id=scenario_id) config_json = ast.literal_eval(emod_scenario.get_file_by_type('config').content) config_json['parameters']['Simulation_Duration'] = 20 * 365 # 20 years emod_scenario.add_file_from_string('config', 'config.json', json.dumps(config_json), description='SOMETHING') my_simulation_duration = config_json['parameters']['Simulation_Duration'] ## Set the run start_date based on location and config's start_time my_start_date = \ datetime.datetime.strptime(emod_scenario.template.climate_start_date, '%Y-%m-%d').date() \ + datetime.timedelta(days=config_json['parameters']['Start_Time']) # Initialize the run run = adapter.save_run(scenario_id=scenario_id, template_id=int(emod_scenario.template.id), start_date=my_start_date, duration=my_simulation_duration, name='calibration-verification', description=str(datetime.datetime.now()), location_ndx=emod_scenario.template.location_key.id, timestep_interval=1, run_id=-1, as_object=True) run.baseline_key_id = scenario_id run.save() # add in JCD for config file changes = [] newdict = copy.deepcopy(config_json) newdict['config.json/parameters'] = newdict.pop('parameters') changes.append(Change.node(name='config.json', node=[newdict], mode='-')) run.jcd = JCD.from_changes(changes) run.save() ### Launch the run # 5853 - hard-code to 1 for now #reps_per_exec = int(self.get_cleaned_data_for_step('start')['reps_per_exec']) reps_per_exec = 1 # submit returns tuple (success, message) try: status = submit(run, user=request.user, manifest=True, reps_per_exec=reps_per_exec) set_notification('alert-success', '<strong>Success!</strong> Run launched.', request.session) except (RuntimeError, TypeError, AssertionError), e: set_notification('alert-error', '<strong>Error!</strong> ' + str(e.message), request.session)
def create_or_update_species(self, request): # Information for the standard attributes. If a species_id of 0 is specified, a new # RepresentativeSpecies entry will be made using these values. If an already existing id is specified, # the current values will stay and these values will be ignored. However, if the id is not 0 and is not an # already existent entry, this will overwrite the current values with these values. species_id = int(request.POST['species_id']) name = request.POST['name'] description = request.POST['description'] emod_snippet_id = int(request.POST['emod_snippet_id']) # If 0 then null. om_snippet_id = int(request.POST['om_snippet_id']) # If 0 then null. if 'is_active' in request.POST: is_active = True else: is_active = False # 0 means we are explicitly requesting a new object, else we are looking for a specific one that supposedly # already exists, but if it doesn't, it will be created anyway if species_id == 0: species = RepresentativeSpecies(name=name, description=description, habitat_type=RepresentativeSpeciesHabitatType.objects.get(id=1), is_active=is_active) else: try: # Does exist, so use current values species = RepresentativeSpecies.objects.get(id=species_id) species.name = name species.description = description species.is_active = is_active except: # Doesn't exist, so fill in with values from above species = RepresentativeSpecies(name=name, description=description, habitat_type=RepresentativeSpeciesHabitatType.objects.get(id=1), is_active=is_active) if emod_snippet_id != 0: try: species.emod_snippet = EMODSnippet.objects.get(id=emod_snippet_id) except: print 'EMOD snippet with id ' + str(emod_snippet_id) + ' does not exist!' raise ValueError('Error') else: print emod_snippet_id raise ValueError('Error') if om_snippet_id != 0: try: species.om_snippet = OMSnippet.objects.get(id=om_snippet_id) except: print 'OM snippet with id ' + str(om_snippet_id) + ' does not exist!' species.save() set_notification('alert-success', '<strong>Success!</strong> Successfully saved.', self.request.session)
def reset_scenario(request): """ Method to clear out all wizard settings and redirect user to beginning """ try: del request.session['wizard_baseline_wizard_view'] if 'scenario' in request.session.keys(): del request.session['scenario'] if 'scenario_config' in request.session.keys(): del request.session['scenario_config'] set_notification('alert-success', 'The simulation was not saved, the settings were cleared. ', request.session) except KeyError: pass return redirect("ts_scenario_step", step='location')
def privatize_scenario(request, baseline_id): try: scenario = DimBaseline.objects.get(id=baseline_id) scenario.is_public = False scenario.save() except ObjectDoesNotExist: raise Http404('Scenario with id %s does not exist.' % baseline_id) set_notification('alert-success', '<strong>Success!</strong> You have successfully made simulation private' , request.session) return redirect("ts_emod_scenario_details", scenario_id=baseline_id)
def reset_scenario(request): """ Method to clear out all wizard settings and redirect user to beginning """ try: del request.session["wizard_baseline_wizard_view"] if "scenario" in request.session.keys(): del request.session["scenario"] if "scenario_config" in request.session.keys(): del request.session["scenario_config"] set_notification("alert-success", "The simulation was not saved, the settings were cleared. ", request.session) except KeyError: pass return redirect("ts_scenario_step", step="location")
def upload(request, file_type, scenario_id): dim_user = DimUser.objects.get(username=request.user.username) scenario = Scenario.objects.get(id=scenario_id) if scenario.user != dim_user: raise PermissionDenied set_notification('alert-success', '<strong>Success!</strong> Saved new json.', request.session) set_notification('alert-error', '<strong>Error!</strong> Failed to save json.', request.session) scenario.set_file_by_type(file_type, request.FILES[file_type].read()) return redirect("ts_emod2.details", scenario_id=scenario_id)
def deleteSpecies(request, species_id): """Function to delete Species DB Objects """ try: species_to_delete = Species.objects.get(id=species_id) species_to_delete.delete() set_notification('alert-success', '<strong>Success!</strong> You have successfully deleted the species.', request.session) except: print 'Error deleting species with id: %s' % species_id set_notification('alert-error', '<strong>Success!</strong> You have successfully deleted the scenario.', request.session) return redirect('ts_emod_scenario_browse')
def publicize_scenario(request, scenario_id): try: scenario = Scenario.objects.get(id=scenario_id) scenario.is_public = True scenario.save() except ObjectDoesNotExist: raise Http404('Scenario with id %s does not exist.' % scenario_id) set_notification('alert-success', '<strong>Success!</strong> You have successfully made the simulation public.', request.session) return redirect("ts_emod2.details", scenario_id=scenario_id)
def error_submit(request): try: sender_email = settings.SERVER_EMAIL server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT) if getattr(settings, 'EMAIL_USE_TLS', True): server.starttls() to = '' for recipient in settings.ADMINS: to += recipient[1] + ',' header = 'To:' + to + '\n' + 'From: ' + sender_email + '\n' + 'Subject:VecNet Server Error (' + request.POST['error_code'] + ') report from ' + request.POST['name'] + '\n\n' msg = header + 'Server Error Form Results: \n\n' msg = msg + 'Error Type: ' + request.POST['error_code'] + '\n' msg = msg + 'Error Reported By: ' + request.POST['name'] + '\n' msg = msg + 'Reporter\'s Email: ' + request.POST['email'] + '\n\n' msg = msg + 'Description of problem: ' + request.POST['rant'] + '\n\n' msg = msg + 'Report timestamp: ' + str(datetime.today()) + '\n\n' try: msg = msg + 'Username: '******'\n\n' except: pass try: msg = msg + "User agent: " + request.META['HTTP_USER_AGENT'] + "\n\n" except: pass try: msg = msg + "URL: " + request.path_info + "?" + request.META['QUERY_STRING'] + "\n\n" except: pass try: msg = msg + 'Session data: ' + "%s" % request.session.load() + '\n\n' except: pass server.sendmail(sender_email, to, msg) server.close() set_notification('alert-success', '<strong>Thank you for your submission!</strong> We will resolve this issue as soon as possible.', request.session) except: set_notification('alert-error', '<strong>Error!</strong> Your response wasn\'t submitted. Please contact us directly at [email protected] for further assistance.', request.session) return redirect(reverse('index'))
def copy_scenario(request, scenario_id): old_scenario = Scenario.objects.get(id=scenario_id) include_output = json.loads(request.POST['include_output']) should_link_experiment = json.loads(request.POST['should_link_experiment']) should_link_simulation = json.loads(request.POST['should_link_simulation']) should_link_simulation_files = json.loads(request.POST['should_link_simulation_files']) new_scenario = old_scenario.copy(include_output, should_link_experiment, should_link_simulation, should_link_simulation_files) goto_url = reverse("ts_emod2.details", kwargs={'scenario_id': new_scenario.id}) set_notification('alert-success', '<strong>Success!</strong> Simulation copied.', request.session) return HttpResponse(content=goto_url)
def done(self, form_list, **kwargs): """A method that processes all the form data at the end of Intervention Tool Process, Save collected data into scenario """ # TODO: still need to handle saving after removing all interventions try: my_campaign = self.storage.extra_data['my_campaign'] my_length = len(my_campaign['Events']) my_config = ast.literal_eval(self.request.session['scenario'].get_file_by_type('config').content) except KeyError: my_length = 0 if my_length > 0: # enable in config if my_config['parameters']['Enable_Interventions'] == 0: my_config['parameters']['Enable_Interventions'] = 1 self.request.session['scenario'].add_file_from_string('config', 'config.json', str(my_config), description="Modified by Intervention Tool") # add in campaign file self.request.session['scenario'].add_file_from_string('campaign', 'campaign.json', str(my_campaign), description="Added by Intervention Tool") set_notification('alert-success', '<strong>Success!</strong> The intervention(s) have been saved to ' + self.request.session['scenario'].name + '.', self.request.session) # check if user wants to launch, or just save if 'launch' in self.storage.data['step_data']['intervention'] \ and str(self.storage.data['step_data']['intervention']['launch'][0]) == '1': launch_flag = True else: launch_flag = False # save this for redirect use my_scenario_id = self.request.session['scenario'].id # clear out saved form data. self.storage.reset() if 'scenario' in self.request.session.keys(): del self.request.session['scenario'] if launch_flag: return redirect("ts_emod_launch_tool", step='start', scenario_id=str(my_scenario_id)) else: return redirect("ts_emod_scenario_details", scenario_id=str(my_scenario_id))
def save_scenario_name(request, scenario_id, scenario_name): scenario = DimBaseline.objects.get(id=scenario_id) # Check to see if this user has permission if scenario.user != DimUser.objects.get_or_create(username=request.user.username)[0]: raise PermissionDenied # Print data print "Scenario name = " + scenario_name # Fill data scenario.name = scenario_name scenario.save() set_notification('alert-success', '<strong>Success!</strong> Successfully updated simulation name.', request.session)
def cancel_edit(request): """ Method to cancel editing a scenario, clear out all wizard settings and redirect user to scenario list """ try: del request.session["wizard_baseline_wizard_view"] if "intervention_id" in request.session.keys(): del request.session["intervention_id"] if "scenario" in request.session.keys(): del request.session["scenario"] if "scenario_config" in request.session.keys(): del request.session["scenario_config"] if "scenario_template_config" in request.session.keys(): del request.session["scenario_template_config"] set_notification("alert-success", "Editing has been canceled.", request.session) except KeyError: pass return redirect("ts_emod_scenario_browse")
def approve_scenario(request, scenario_id): """ Method to allow a user to approve a scenario (without going through the wizard) """ try: # get the scenario my_scenario = EMODBaseline.from_dw(pk=scenario_id) # check for run results # ToDo: check for run results # set approved, save my_scenario.is_approved = True my_scenario.save() set_notification('alert-success', 'The simulation was approved. ', request.session) except: set_notification('alert-error', 'An Error occurred: the simulation was not approved. ', request.session) return redirect("ts_emod_scenario_details", scenario_id=scenario_id)
def saveNote(request, run_id, note_id=None ): """Function to save Note DB Objects """ if request.method == 'POST': #note = Note(text=request.POST.get('text'), run_key_id=run_id) #note.save() if run_id == None: run_id = request.POST.get('run_id') adapter = EMOD_Adapter(request.user.username) note_id = adapter.save_note(run_id, note=request.POST.get('text')) if note_id != None: set_notification('alert-success','<strong>Success!</strong> You have successfully saved the note.', request.session) else: set_notification('alert-error','<strong>Error!</strong> There was a problem saving the note.', request.session) return redirect(request.environ['HTTP_REFERER'])
def send_calibration_request_ajax(request, scenario_id): try: unformatted_targets_json = json.loads(request.body) except: set_notification('alert-error', '<strong>Error!</strong> Malformed request.body json.', request.session) return HttpResponse() targets_json = {} targets_json['sporozoite'] = [] targets_json['eir'] = [] for species in unformatted_targets_json: targets_json['sporozoite'].append(unformatted_targets_json[species]['sporozoite']) targets_json['eir'].append(unformatted_targets_json[species]['eir']) send_calibration_request(request, targets_json, scenario_id) return HttpResponse()
def done(self, form_list, **kwargs): """A method that processes all the form data at the end of BaselineWizard Process then Save collected data from multiple forms into one DB table (Baseline) """ # check to make sure at least one run has been done self.request.session['scenario'].is_approved = True my_id, completed = self.request.session['scenario'].save() if my_id == self.request.session['scenario'].id: # reset session variables del self.request.session['scenario'] del self.request.session['scenario_config'] set_notification('alert-success', '<strong>Success!</strong> Successfully saved.', self.request.session) return redirect("ts_emod_scenario_browse")
def cancel_edit(request): """ Method to cancel editing a scenario, clear out all wizard settings and redirect user to scenario list """ try: del request.session['wizard_baseline_wizard_view'] if 'intervention_id' in request.session.keys(): del request.session['intervention_id'] if 'scenario' in request.session.keys(): del request.session['scenario'] if 'scenario_config' in request.session.keys(): del request.session['scenario_config'] if 'scenario_template_config' in request.session.keys(): del request.session['scenario_template_config'] set_notification('alert-success', 'Editing has been canceled.', request.session) except KeyError: pass return redirect("ts_emod_scenario_browse")
def render_done(self, form, **kwargs): """ Override the wizard's default render_done This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # add in our own checks, fail validation here, so wizard isn't reset if we need to go back if not self.request.session['scenario'].has_required_files: my_missing = self.request.session['scenario'].get_missing_files() if len(my_missing) == 0: my_missing = "" else: my_missing = "Missing files: " + str(my_missing) set_notification('alert-error', '<strong>Error!</strong> This simulation is incomplete. ' + my_missing + ' Please go back and complete before approving.', self.request.session) form_key = 'review' form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) return self.render_revalidation_failure(form_key, form_obj, **kwargs) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response
def folder_delete(request, folder_id): """ Function to delete Folder DB Objects Input: folder_id: id of folder to be deleted - Only deletes folder if it's empty (displays error if not) """ my_parent = 0 folder_to_delete = Folder.objects.get(id=folder_id) if folder_to_delete.parent is not None: my_parent = str(folder_to_delete.parent.id) else: my_parent = None test = folder_to_delete.delete() if test is True: set_notification('alert-success', '<strong>Success!</strong> You have successfully deleted the folder.', request.session) elif test == 'NotEmpty': set_notification('alert-error', '<strong>Error!</strong> You cannot delete the folder because it is not empty. ' 'Please remove all simulations and folders from it before deleting.', request.session) # go to folder that wasn't deleted because it wasn't empty - show user what's in there return redirect("ts_emod_scenario_browse", folder_id=str(folder_to_delete.id)) else: print 'Error deleting folder with id: %s' % folder_id set_notification('alert-error', '<strong>Error!</strong> There was a problem deleting the folder.', request.session) if my_parent is None: # return to the home/root folder return redirect("ts_emod_scenario_browse") else: # return to the parent folder return redirect("ts_emod_scenario_browse", folder_id=str(my_parent))
def post(self, request): csvUploadForm = CsvUploadForm(prefix='csvUploadForm') climateUploadForm = ClimateUploadForm(prefix='climateUploadForm') action = self.request.POST['action'] print("Before csv creation " + time.strftime("%M:%S")) if action == 'uploadCsv': csvUploadForm = CsvUploadForm(request.POST, request.FILES, prefix='csvUploadForm') if csvUploadForm.is_valid(): try: csvData, nodeIDs = self.getCsvDataFromCsv(request.FILES['csvUploadForm-csvFile']) except DateException as exception: # There was a bad date set_notification('alert-error', 'File failed validation. ' + exception.message, self.request.session) context = { 'csvUploadForm': csvUploadForm, 'climateUploadForm': climateUploadForm, } return render(request, 'ts_weather/index.html', context) except: # There was an error with the files set_notification('alert-error', 'File failed validation.', self.request.session) context = { 'csvUploadForm': csvUploadForm, 'climateUploadForm': climateUploadForm, } return render(request, 'ts_weather/index.html', context) dataTypeName = csvUploadForm['dataType'].value() context = { 'csvUploadForm': csvUploadForm, 'csvData': csvData, 'nodeIDs': nodeIDs, 'dataTypeName': dataTypeName, 'formType': "emod", } return render(request, 'ts_weather/visualizer.html', context) elif action == 'uploadEmod': climateUploadForm = ClimateUploadForm(request.POST, request.FILES, prefix='climateUploadForm') if climateUploadForm.is_valid(): jsonFile = request.FILES['climateUploadForm-jsonFile'] binFile = request.FILES['climateUploadForm-binFile'] print("After csv creation " + time.strftime("%M:%S")) try: csvData, nodeIDs = self.getCsvDataFromEmod(jsonFile, binFile) except: # There was an error with the files set_notification('alert-error', 'Files failed validation.', self.request.session) context = { 'csvUploadForm': csvUploadForm, 'climateUploadForm': climateUploadForm, } return render(request, 'ts_weather/index.html', context) print("After csv extraction " + time.strftime("%M:%S")) dataTypeName = climateUploadForm['dataType'].value() context = { 'climateUploadForm': climateUploadForm, 'csvData': csvData, 'nodeIDs': nodeIDs, 'dataTypeName': dataTypeName, 'formType': "csv", } return render(request, 'ts_weather/visualizer.html', context) return render(request, 'ts_weather/index.html', {}) # Just an error
def folder_save(request): """ Function to save Folder DB Objects - Takes the form data posted and uses it to make a new folder - folder_id is the new folder's parent """ if request.POST.get('folder-name') == '': set_notification('alert-error', '<strong>Error!</strong> Please name the folder.', request.session) return redirect("ts_emod_scenario_browse") if request.method == 'POST': if request.POST.get('folder_id') is not None and request.POST.get('folder_id') != '': parent = Folder.objects.get(pk=int(request.POST.get('folder_id'))) else: parent = None folder = Folder(name=request.POST.get('folder-name'), description=request.POST.get('folder-description'), parent=parent, user=DimUser.objects.get(username=request.user.username), sort_order=0) folder.save() if folder.id is not None: set_notification('alert-success', '<strong>Success!</strong> You have successfully created the folder %s.' % folder.name, request.session) else: set_notification('alert-error', '<strong>Error!</strong> There was a problem saving the folder.', request.session) return redirect("ts_emod_scenario_browse", folder_id=str(folder.id))
def delete_run(request, scenario_id, run_id): """Function to allow deletion of run DB Objects """ try: # adapter = EMOD_Adapter(request.user.username) my_run = DimRun.objects.get(pk=run_id) my_name = my_run.name if request.user.is_authenticated() \ and str(DimBaseline.objects.get(id=scenario_id).user) == str(request.user.username): # adapter.delete_run(int(run_id)) my_run.is_deleted = True my_run.time_deleted = datetime.datetime.now() my_run.save() set_notification('alert-success', '<strong>Success!</strong> You have successfully deleted the run ' + my_name, request.session) else: set_notification('alert-error', '<strong>Error!</strong> Please log in before deleting. ' 'Run was not deleted.', request.session) except: print 'Error deleting run with id: %s' % run_id set_notification('alert-error', '<strong>Error!</strong> Run was not deleted.', request.session) return redirect("ts_emod_scenario_details", scenario_id=str(scenario_id))