Reputation: 107
I am trying to recreate the game of hacks because there isn't an API to create my own questions, and implement on external site , however I am using django with restful framework for this task. (I am not sure , if this is the right to achieve this). I will do this via server because I dont want people to change js and bypass the stuff or even disable js and stop time , and continue with the same question, but how can I translate into django this?
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Question, Choice
from .serializers import QuestionListPageSerializer, QuestionDetailPageSerializer, ChoiceSerializer, VoteSerializer, QuestionResultPageSerializer
@api_view(['GET', 'POST'])
def questions_view(request):
if request.method == 'GET':
questions = Question.objects.all()
serializer = QuestionListPageSerializer(questions, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = QuestionListPageSerializer(data=request.data)
if serializer.is_valid():
question = serializer.save()
return Response(QuestionListPageSerializer(question).data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class QuestionListPageSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
question_text = serializers.CharField(max_length=200)
pub_date = serializers.DateTimeField()
was_published_recently = serializers.BooleanField(read_only=True) # Serializer is smart enough to understand that was_published_recently is a method on Question
code = serializers.CharField(max_length=200)
def create(self, validated_data):
return Question.objects.create(**validated_data)
def update(self, instance, validated_data):
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
return instance
python test case
import random
import pprint
def pick_ten(fname):
question_list = []
for question in open(fname):
# strip off new line character
question = question.rstrip()
question_list.append(question)
return random.sample(question_list, 1)
# testing ...
filename = "Questions101.txt"
question_list = pick_ten(filename)
pprint.pprint(question_list)
response test case
xxxxxx@xxxxxx:~$ python3 quiz.py
['What was the first brand name for Bubble Gum?']
xxxxxx@xxxxxx:~$ python3 quiz.py
['Which game uses the phrase "en passant"?']
xxxxxx@xxxxxx:~$ python3 quiz.py
['What type of organism causes malaria?']
xxxxxx@xxxxxx:~$
Upvotes: 1
Views: 151
Reputation: 51988
You can do it like this using order_by('?')
:
# random_questions.py
from quizapp.models import Question
def pick_random():
return Question.objects.all().order_by('?').first()
if __name__ == '__main__':
question = pick_random()
print(question.question_text)
# run
python manage.py shell < /path/to/random_questions.py
Upvotes: 1