def update_question(request): token = request.META['HTTP_AUTHORIZATION'].split(' ') try: user = Token.objects.get(key=token[1]).user except Token.DoesNotExist: return JsonResponse({"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED) question = request.data.get('Question') questionData = Question.objects.filter(id=question['id']) if len(questionData) == 0: return JsonResponse({"error": "There is no question with this id"}, status=status.HTTP_401_UNAUTHORIZED) ques = QuestionSerializer(questionData[0], many=False).data print(ques) if ques['user'] != user.id: return JsonResponse( { "error": "Cannot update the question .The questions can only be updated by the user who created" }, status=status.HTTP_401_UNAUTHORIZED) cats = Category.objects.filter(name=question['category']) if len(cats) == 0: return JsonResponse({"error": "Enter valid category"}, status=status.HTTP_400_BAD_REQUEST) try: index = question['options'].index(question['answer']) except Exception as error: return JsonResponse({"error": "There is no option with the answer "}, status=status.HTTP_400_BAD_REQUEST) category = CategorySerializer(cats, many=True).data options = question['options'] if len(options) != 4: return JsonResponse({"error": "There should be exaclty 4 options"}, status=status.HTTP_400_BAD_REQUEST) optionsList = [] for option in options: optionData = Options.objects.filter(option=option) if len(optionData) == 0: option = {'option': option} serializer = OptionsSerializer(data=option, many=False) if serializer.is_valid(): serializer.save() else: serializer = OptionsSerializer(optionData[0], many=False) optionsList.append(serializer.data['option']) questionData = Question.objects.get(id=question['id']) questionData.question = question['question'] questionData.category = Category.objects.get(name=category[0]['name']) questionData.options.set(optionsList) questionData.user = user questionData.answer = Options.objects.get(option=optionsList[index]) questionData.save() serializer = QuestionSerializer(questionData) return JsonResponse({"data": serializer.data}, status=status.HTTP_200_OK)
def delete_question(request): token = request.META['HTTP_AUTHORIZATION'].split(' ') if "id" not in request.data: return JsonResponse( {"error": "Enter question ID"}, status=status.HTTP_400_BAD_REQUEST ) try: user = Token.objects.get(key=token[1]).user except Token.DoesNotExist: return JsonResponse( {"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED ) questionData = Question.objects.filter(id=request.data['id']) if len(questionData) == 0: return JsonResponse( {"error": "There is no question with this id"}, status=status.HTTP_401_UNAUTHORIZED ) ques = QuestionSerializer(questionData[0], many=False).data if ques['user'] != user.id: return JsonResponse( {"error": "Cannot delete the question .The questions can only be deleted by the user who created"}, status=status.HTTP_401_UNAUTHORIZED ) Question.objects.filter(id=request.data['id']).delete() return JsonResponse( {"question": "Question deleted sucessfully"}, status=status.HTTP_204_NO_CONTENT )
def check_if_game_code_isValid(request): if "game_code" not in request.data: return JsonResponse( {"error": "Enter game_code"}, status=status.HTTP_400_BAD_REQUEST ) if "user_name" not in request.data: return JsonResponse( {"error": "Enter user_name"}, status=status.HTTP_400_BAD_REQUEST ) try: game = Game.objects.get(game_code=request.data['game_code']) gameData = GameSerializer(game).data if gameData['user_name'] == request.data['user_name']: return JsonResponse({"error": "Admin cannot play the game"}, status=status.HTTP_400_BAD_REQUEST) if gameData['active']: ug = UserGames.objects.filter(game_code=request.data['game_code'], user_name=request.data['user_name']) if len(ug) != 0: return JsonResponse({ "error": "Already played game" }, status=status.HTTP_400_BAD_REQUEST) qList = Question.objects.filter(category=gameData['category']).values_list('id', flat=True) qRand = random.sample(list(qList), min(len(qList), 10)) questions = Question.objects.filter(id__in=qRand) questionData = QuestionSerializer(questions, many=True).data questions = [] for question in questionData: options = [] for option in question['options']: optionQuery = Options.objects.get(option=option) optionData = OptionsSerializer(optionQuery, many=False).data options.append(optionData['option']) question['options'] = options questions.append(question) serializer = UserGamesSerializer(data={ 'game_code': request.data['game_code'], 'category': gameData['category'], 'user_name': request.data['user_name'] }) if serializer.is_valid(): serializer.save() return JsonResponse({ "data": { 'questions': questions, 'usergameData': serializer.data } }, status=status.HTTP_200_OK) return JsonResponse({ "error": serializer.errors }, status=status.HTTP_400_BAD_REQUEST) else: return JsonResponse({"error": "Game code is expired"}, status=status.HTTP_400_BAD_REQUEST) except Game.DoesNotExist: return JsonResponse({ "error": "Invalid game code" }, status=status.HTTP_400_BAD_REQUEST) except Exception as error: return JsonResponse({"error": error}, status=status.HTTP_400_BAD_REQUEST)
def create_question(request): token = request.META['HTTP_AUTHORIZATION'].split(' ') try: user = Token.objects.get(key=token[1]).user except Token.DoesNotExist: return JsonResponse( {"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED ) question = request.data.get('Question') cats = Category.objects.filter(name=question['category']) if len(cats) == 0: return JsonResponse( {"error": "Enter valid category"}, status=status.HTTP_400_BAD_REQUEST ) try: index = question['options'].index(question['answer']) except Exception as error: return JsonResponse( {"error": "There is no option with the answer "}, status=status.HTTP_400_BAD_REQUEST ) category = CategorySerializer(cats, many=True).data options = question['options'] if len(options) != 4: return JsonResponse( {"error": "There should be exaclty 4 options"}, status=status.HTTP_400_BAD_REQUEST ) optionsList = [] for option in options: optionData = Options.objects.filter(option=option) if len(optionData) == 0: option = { 'option': option } serializer = OptionsSerializer(data=option, many=False) if serializer.is_valid(): serializer.save() else: serializer = OptionsSerializer(optionData[0], many=False) optionsList.append(serializer.data['option']) question = { "question": question['question'], "category": category[0]['name'], "options": optionsList, "user": user.id, "answer": optionsList[index] } serializer = QuestionSerializer(data=question) if serializer.is_valid(): serializer.save() return JsonResponse({ "data": serializer.data }, status=status.HTTP_200_OK) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_questions_user(request): token = request.META['HTTP_AUTHORIZATION'].split(' ') try: user = Token.objects.get(key=token[1]).user except Token.DoesNotExist: return JsonResponse({"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED) questions = Question.objects.filter(user=user.id) questionData = QuestionSerializer(questions, many=True).data questions = [] for question in questionData: options = [] for option in question['options']: optionQuery = Options.objects.get(option=option) optionData = OptionsSerializer(optionQuery, many=False).data options.append(optionData['option']) question['options'] = options questions.append(question) return JsonResponse({"data": questions}, status=status.HTTP_200_OK)
def opendb(request): # User Authorization to ensure only user who adds questions can delete/edit them token = request.META['HTTP_AUTHORIZATION'].split(' ') try: user = Token.objects.get(key=token[1]).user except Token.DoesNotExist: return JsonResponse( {"error": "Invalid token"}, status=status.HTTP_401_UNAUTHORIZED ) data = requests.get(url=request.data['url']).json() # takes in data from url and displays json response # print(data) #testing questions_to_serialize = [] # question list optionsList = [] # option list for option_data in data.get('results', []): # get data starting from 'results' in JSON response (LOOP 1) options = option_data.get('incorrect_answers') for option in options: # goes through option list (LOOP 2) optionData = Options.objects.filter(option=option) if len(optionData) == 0: option = { 'option': option, } serializer = OptionsSerializer(data=option, many=False) if serializer.is_valid(): serializer.save() else: serializer = OptionsSerializer(optionData[0], many=False) optionsList.append(serializer.data['option']) # gets correct answer and appends it to the end of the options list option = {'option': option_data.get('correct_answer')} serializer_ans = OptionsSerializer(data=option, many=False) if serializer_ans.is_valid(): serializer_ans.save() optionsList.append(serializer_ans.data['option']) # print(optionsList) # print(data) # questions for question_data in data.get('results', []): # fixes HTML encoding unescapedquestion = question_data.get('question') escapedquestion = html.unescape(unescapedquestion) formattedquestion = escapedquestion.replace("\\", "") # gets question data QuestionData = { "category": question_data.get('category'), "type": question_data.get('type'), "difficulty": question_data.get('difficulty'), "options": optionsList, # gets options from option list "question": formattedquestion, # takes in formated question "user": user.id, # takes in user id "answer": optionsList[3], # sets the last entry as the answer from option list } questions_to_serialize.append(QuestionData) # optionsList.clear() serializer = QuestionSerializer(data=questions_to_serialize, many=True) # print(QuestionData) if serializer.is_valid(): serializer.save() return JsonResponse({ "data": serializer.data }, status=status.HTTP_200_OK) return JsonResponse(serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST)
def check_if_game_code_isValid(request): if "isGeneral" not in request.data: if "game_code" not in request.data: return JsonResponse( {"error": "Enter game_code"}, status=status.HTTP_400_BAD_REQUEST ) if "user_name" not in request.data: return JsonResponse( {"error": "Enter user_name"}, status=status.HTTP_400_BAD_REQUEST ) game = Game.objects.get(game_code=request.data['game_code']) gameData = GameSerializer(game).data category = gameData['category'] if gameData['user_name'] == request.data['user_name']: return JsonResponse({"error": "Admin cannot play the game"}, status=status.HTTP_400_BAD_REQUEST) if not gameData['active']: return JsonResponse({"error": "Game code is expired"}, status=status.HTTP_400_BAD_REQUEST) else: ug = UserGames.objects.filter(game_code=request.data['game_code'], user_name=request.data['user_name']) if len(ug) != 0: return JsonResponse({ "error": "Already played game" }, status=status.HTTP_400_BAD_REQUEST) data = { 'game_code': request.data['game_code'], 'category': gameData['category'], 'user_name': request.data['user_name'] } else: if "email_address" not in request.data: return JsonResponse( {"error": "Enter email_address"}, status=status.HTTP_400_BAD_REQUEST ) if "category" not in request.data: return JsonResponse( {"error": "Enter category"}, status=status.HTTP_400_BAD_REQUEST ) categories = Category.objects.filter(name=request.data['category']) if len(categories) == 0: return JsonResponse( {"error": "Enter valid category"}, status=status.HTTP_400_BAD_REQUEST ) if categories[0].isSubCategory: parentCategoryId = categories[0].parentCategory allCategories = Category.objects.filter(parentCategory=parentCategoryId) ug = UserGames.objects.filter(email_address=request.data['email_address'], category__in=allCategories) if len(ug) != 0: return JsonResponse({ "error": "Already played game" }, status=status.HTTP_400_BAD_REQUEST) else: ug = UserGames.objects.filter(email_address=request.data['email_address'], category=request.data['category']) if len(ug) != 0: return JsonResponse({ "error": "Already played game" }, status=status.HTTP_400_BAD_REQUEST) category = request.data['category'] data = { 'category': category, 'email_address': request.data['email_address'] } try: qList = Question.objects.filter(category=category).values_list('id', flat=True) qRand = random.sample(list(qList), min(len(qList), 10)) questions = Question.objects.filter(id__in=qRand) questionData = QuestionSerializer(questions, many=True).data questions = [] for question in questionData: options = [] for option in question['options']: optionQuery = Options.objects.get(option=option) optionData = OptionsSerializer(optionQuery, many=False).data options.append(optionData['option']) question['options'] = options questions.append(question) serializer = UserGamesSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse({ "data": { 'questions': questions, 'usergameData': serializer.data } }, status=status.HTTP_200_OK) return JsonResponse({ "error": serializer.errors }, status=status.HTTP_400_BAD_REQUEST) except Game.DoesNotExist: return JsonResponse({ "error": "Invalid game code" }, status=status.HTTP_400_BAD_REQUEST) except Exception as error: return JsonResponse({"error": error}, status=status.HTTP_400_BAD_REQUEST)