def write_new(request, methods=['POST']): if request.POST['question'] and request.POST['choice1'] and request.POST['choice2']: q=Question() q.title=request.POST['question'] q.save() c1=Choice() c1.questions=q c1.options=request.POST['choice1'] c1.save() c2=Choice() c2.questions=q c2.options=request.POST['choice2'] c2.save() if request.POST['choice3']: c3=Choice() c3.questions=q c3.options=request.POST['choice3'] c3.save() if request.POST['choice4']: c4=Choice() c4.questions=q c4.options=request.POST['choice4'] c4.save() if request.POST['choice5']: c5=Choice() c5.questions=q c5.options=request.POST['choice5'] c5.save() return HttpResponseRedirect('/poll/')
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)