def scenario(request, scen_id): """Retrieve, update or delete a scenario""" scenario = get_object_or_404(Scenario, id=scen_id) if request.method == 'GET': if (scenario.project.user.id != request.user.id and scenario.project.is_private): return Response(status=status.HTTP_404_NOT_FOUND) serializer = ScenarioSerializer(scenario) return Response(serializer.data) elif scenario.project.user.id == request.user.id: if request.method == 'PUT': ctx = {'request': request} serializer = ScenarioSerializer(scenario, data=request.data, context=ctx) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': scenario.delete() return Response(status=status.HTTP_204_NO_CONTENT) else: return Response(status=status.HTTP_404_NOT_FOUND)
def scenarios(request): """Create a scenario for projects which authenticated user has access to""" if request.method == 'POST': serializer = ScenarioSerializer(data=request.data, context={"request": request}) project_id = serializer.initial_data.get('project') get_object_or_404(Project, id=project_id, user=request.user) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def scenario_duplicate(request, scen_id): """Duplicate a scenario.""" scenario = get_object_or_404(Scenario, id=scen_id) if scenario.project.user != request.user: return Response(status=status.HTTP_404_NOT_FOUND) scenario.pk = None scenario.is_current_conditions = False # Give the scenario a new name. Same logic as in # modeling/models.js:makeNewScenarioName. names = scenario.project.scenarios.values_list('name', flat=True) copy_name = 'Copy of {}'.format(scenario.name) copy_counter = 1 while copy_name in names: copy_name = 'Copy of {} {}'.format(scenario.name, copy_counter) copy_counter += 1 scenario.name = copy_name scenario.save() serializer = ScenarioSerializer(scenario) return Response(serializer.data, status=status.HTTP_201_CREATED)