Exemplo n.º 1
0
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)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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)