def create_poll(request): """ Allows admins to create a new poll """ user = request.user if not user.is_staff: return Response({"message": "Unauthorized"}, status=401) data = request.data try: title = str(data["title"]) questions = data["questions"] try: poll = Poll.objects.get(title=title) return Response({"message": "Poll with this title already exists"}, status=412) except Poll.DoesNotExist: poll = Poll.objects.create(title=title) try: if data["min_age"] != "": poll.min_age = int(data["min_age"]) except: pass try: if data["max_age"] != "": poll.max_age = int(data["max_age"]) except: pass try: if data["min_income"] != "": poll.min_income = int(data["min_income"]) except: pass try: if data["max_income"] != "": poll.max_income = int(data["max_income"]) except: pass for question in questions: valid_categories = ["MCSO", "MCMO", "OWNI", "S", "E"] try: question_title = str(question["question_title"]) category = str(question["category"]) if category not in valid_categories: poll.delete() return Response({"message": "Invalid question category"}, status=412) try: optional = question["optional"] valid_optionals = [True, False] if optional not in valid_optionals: poll.delete() return Response( {"message": "Invalid value for optional"}, status=412) except: optional = False question = Question() question.title = question_title question.category = category question.optional = optional question.poll = poll question.save() except KeyError as missing_data: poll.delete() return Response( {'message': 'Data is Missing: {}'.format(missing_data)}, status=400) return Response({"message": "Poll created!"}, status=201) except KeyError as missing_data: return Response( {'message': 'Data is Missing: {}'.format(missing_data)}, status=400)