как я могу иметь таймер в нашем вопросе? Django - PullRequest
0 голосов
/ 20 января 2020

у нас есть набор вопросов для опроса с максимум 20 вопросами в опросе, но мы сможем выбрать не более 5 случайных вопросов, по одному на этап, но я не хочу, чтобы люди могли обманывать время только путем проверки на стороне клиента, но каждый вопрос имеет время 1 минута, как только он истекает, следующий будет.

модели

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    duration = models.IntegerField(min=0, max=60)
    code = models.TextField(max_length=1024*2,default='SOME STRING')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def choices(self):
        if not hasattr(self, '_choices'):
            self._choices = self.choice_set.all()
        return self._choices

    def max_voted_choice(self):
        if not hasattr(self, '_max_voted_choice'):
            choices = self.choice_set.order_by('-votes')
            if not choices:
                self._max_voted_choice = None
            else:
                self._max_voted_choice = choices[0]
        return self._max_voted_choice



class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

apiviews получить случайный квест ios от опрос

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
import random

@api_view(['GET', 'POST'])
def questions_view(request):
    if request.method == 'GET':
        questions = Question.objects.all().order_by('?')[:5].first()
        serializer = QuestionListPageSerializer(questions)
        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

1 Ответ

0 голосов
/ 21 января 2020

Если я правильно понимаю ваш вопрос, вы хотите иметь таймер, который отсчитывается на странице с вопросом.

Это больше похоже на то, что вы должны реализовать в JavaScript, а не в Django (что-то вроде этого https://www.w3schools.com/howto/howto_js_countdown.asp).

Любое обработанное действие затем отправляется на сервер Django через вызовы API с помощью ajax. Вот учебник о том, как работать, сделать это https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

Надеюсь, это поможет или направит вас в правильном направлении

...