Как показать результаты викторины, используя Angular (и Django в качестве бэкэнда)? - PullRequest
0 голосов
/ 28 мая 2020

Я пишу программу-викторину. Я использую Django для бэкэнда и Angular для внешнего интерфейса. Я не знаю, как отобразить результат теста в Angular. Оценка рассчитывается в Django, и теперь она должна быть показана после отправки всех ответов в Angular
Это мой код

Django
api. py

...
    class SubmitQuizAPI(generics.GenericAPIView):
    serializer_class = QuizResultSerializer
    permission_classes = [
        permissions.IsAuthenticated
    ]

    def post(self, request, *args, **kwargs):
        quiztaker_id = request.data['quiztaker']
        question_id = request.data['question']
        answer_id = request.data['answer']

        quiztaker = get_object_or_404(QuizTaker, id=quiztaker_id)
        question = get_object_or_404(Question, id=question_id)

        quiz = Quiz.objects.get(slug=self.kwargs['slug'])

        if quiztaker.completed:
            return Response({
                "message": "Quiz zakonczony."},
                status=status.HTTP_412_PRECONDITION_FAILED
            )

        if answer_id is not None:
            answer = get_object_or_404(Answer, id=answer_id)
            obj = get_object_or_404(UsersAnswer, quiz_taker=quiztaker, question=question)
            obj.answer = answer
            obj.save()

        quiztaker.completed = True
        correct_answers = 0

        for users_answer in UsersAnswer.objects.filter(quiz_taker=quiztaker):
            answer = Answer.objects.get(question=users_answer.question, is_correct=True)
            print(answer)
            print(users_answer.answer)
            if users_answer.answer == answer:
                correct_answers += 1

        quiztaker.score = int(correct_answers / quiztaker.quiz.question_set.count() * 100)
        print(quiztaker.score)
        quiztaker.save()


settings.py

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'knox',
    'nested_admin',
    'accounts',
    'quiz',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'knox.auth.TokenAuthentication',
   ),
       'UNICODE_JSON': False
}


Angular
quiz-detail.component.ts


import { QuizzesService } from 'src/app/services/quizzes.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-quiz-detail',
  templateUrl: './quiz-detail.component.html',
  styleUrls: ['./quiz-detail.component.scss']
})
export class QuizDetailComponent implements OnInit {
  slug;
  quiz: any;
  currentIndex: number = 0;
  selectedAnswer: number;
  answers = [];


  constructor(
    private route: ActivatedRoute,
    private quizzesService: QuizzesService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.slug = this.route.snapshot.params.slug;
    this.quizzesService.getQuiz(this.slug).subscribe((res) => {
      this.quiz = res['quiz'];
      if(this.quiz.quiztakers_set.completed) {
        this.router.navigate(['/quizzes/' + this.slug + '/result']);
      }
      this.initializeAnswers();
    });
  }

  initializeAnswers() {
    const usersAnswers = this.quiz.quiztakers_set.usersanswer_set;
    for(let i=0; i<usersAnswers.length; i++) {
      this.answers.push(usersAnswers[i]['answer']);
    }
    console.log(this.answers);
  }

  saveAnswer() {
    const body = {
      "quiztaker": this.quiz.quiztakers_set.id,
      "question": this.quiz.question_set[this.currentIndex].id,
      "answer": this.selectedAnswer
    }

    this.quizzesService.saveAnswer(body).subscribe((res) => {
      console.log(res);
    });
  }

  submitQuiz() {
    const body = {
      "quiztaker": this.quiz.quiztakers_set.id,
      "question": this.quiz.question_set[this.currentIndex].id,
      "answer": this.selectedAnswer
    }

    this.quizzesService.submitQuiz(body, this.slug).subscribe((res) => {
      this.router.navigate(['/quizzes/' + this.slug + '/result']); 
    });
  }

  next() {
    if(this.currentIndex === this.quiz.question_set.length-1) {
      this.submitQuiz();
      return;
    }

    if(this.selectedAnswer!=null) {
      this.saveAnswer();
    }

    if(this.currentIndex !== this.quiz.question_set.length-1) {
      this.currentIndex += 1;
      this.selectedAnswer = null;
    }
  }

  selectAnswer(id: number) {
    console.log(id);
    this.selectedAnswer = id;
    this.answers[this.currentIndex] = id;
  }


  previous() {
    if(this.selectedAnswer!=null) {
      this.saveAnswer();
    }

    if(this.currentIndex != 0) {
      this.currentIndex -= 1;
      this.selectedAnswer = null;
    }
  }}


В моем компоненте результата пока что столько:
quiz-result.component.ts


    import { Component, OnInit } from '@angular/core';
import { QuizzesService } from 'src/app/services/quizzes.service';

@Component({
  selector: 'app-quiz-result',
  templateUrl: './quiz-result.component.html',
  styleUrls: ['./quiz-result.component.scss']
})
export class QuizResultComponent implements OnInit {
  quiz: any;
  answers = [];
  correct_answers: number;
  quiztakerScore: number;


  constructor(
    private quizzesService: QuizzesService,
  ) { }

  ngOnInit(): void {
    this.showResult();
  }

showResult() {

}

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...