我收到 questions.models.Question.DoesNotExist:问题匹配查询不存在。当我在测验应用程序中按下保存按钮时

问题描述 投票:0回答:0

这是我得到的回溯

Traceback (most recent call last):
File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner
response = get_response(request)
File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in \_get_response
response = wrapped_callback(request, \*callback_args, \*\*callback_kwargs)
File "/home/kali/django-test-app/src/django-test-app/testapp/quizes/views.py", line 46, in save_quiz_view
question = Question.objects.get(text=k)
File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(\*args, \*\*kwargs)
File "/home/kali/django-test-app/venv/lib/python3.10/site-packages/django/db/models/query.py", line 650, in get
raise self.model.DoesNotExist(
questions.models.Question.DoesNotExist: Question matching query does not exist.
\[01/Apr/2023 13:30:02\] "POST /3/save/ HTTP/1.1" 500 76917

我正在使用 request.is_ajax() 然后我意识到它已被删除所以我将其更改为

if request.headers.get('x-requested-with') == 'XMLHttpRequest':
它没有用,我还尝试创建一个检查功能

def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

并在 request.is_ajax() 时使用: 仍然收到 questions.models.Question.DoesNotExist: 问题匹配查询不存在。 **这是我的views.py **

from django.shortcuts import render
from .models import Quiz
from django.views.generic import ListView
from django.http import JsonResponse
from questions.models import Question, Answer
from results.models import Result
from django.shortcuts import HttpResponse
from django.shortcuts import get_object_or_404

class QuizListView(ListView):
model = Quiz
template_name = 'quizes/main.html'

def quiz_view(request, pk):
quiz = Quiz.objects.get(pk=pk)
return render(request, 'quizes/quiz.html', {'obj': quiz})

def quiz_data_view(request, pk):
quiz = Quiz.objects.get(pk=pk)
questions = \[\]
for q in quiz.get_questions():
answers = \[\]
for a in q.get_answers():
answers.append(a.text)
questions.append({str(q): answers})
return JsonResponse({
'data': questions,
'time': quiz.time,
})

def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def save_quiz_view(request, pk):
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
\# if request.is_ajax():
\# if request.accepts('application/x-www-form-urlencoded'):
questions = \[\]
data = request.POST
data\_ = dict(data.lists())

        data_.pop('csrfmiddlewaretoken')
    
        for k in data_.keys():
            print('key: ', k)
            question = Question.objects.get(text=k)
            questions.append(question)
        print(questions)
    
        user = request.user
        quiz = Quiz.objects.get(pk=pk)
    
        score = 0
        multiplier = 100 / quiz.number_of_questions
        results = []
        correct_answer = None
    
        for q in questions:
            a_selected = request.POST.get(q.text)
    
            if a_selected != "":
                question_answers = Answer.objects.filter(question=q)
                for a in question_answers:
                    if a_selected == a.text:
                        if a.correct:
                            score += 1
                            correct_answer = a.text
                    else:
                        if a.correct:
                            correct_answer = a.text
    
                results.append({str(q): {'correct_answer': correct_answer, 'answered': a_selected}})
            else:
                results.append({str(q): 'not answered'})
            
        score_ = score * multiplier
        Result.objects.create(quiz=quiz, user=user, score=score_)
    
        if score_ >= quiz.required_score_to_pass:
            return JsonResponse({'passed': True, 'score': score_, 'results': results})
        else:
            return JsonResponse({'passed': False, 'score': score_, 'results': results})

这是ajax函数


    $.ajax({
        headers: { "X-CSRFToken": csrftoken },
        type: 'POST',
        url: `${url}save/`,
        data: data,
        success: function(response){
            const results = response.results
            console.log(results)
            quizForm.classList.add('not-visible')

            scoreBox.innerHTML = `${response.passed ? 'Congratulations! ' : 'Ups..:( '}Your result is ${response.score.toFixed(2)}%`

            results.forEach(res=>{
                const resDiv = document.createElement("div")
                for (const [question, resp] of Object.entries(res)){

                    resDiv.innerHTML += question
                    const cls = ['container', 'p-3', 'text-light', 'h6']
                    resDiv.classList.add(...cls)

                    if (resp=='not answered') {
                        resDiv.innerHTML += '- not answered'
                        resDiv.classList.add('bg-danger')
                    }
                    else {
                        const answer = resp['answered']
                        const correct = resp['correct_answer']

                        if (answer == correct) {
                            resDiv.classList.add('bg-success')
                            resDiv.innerHTML += ` answered: ${answer}`
                        } else {
                            resDiv.classList.add('bg-danger')
                            resDiv.innerHTML += ` | correct answer: ${correct}`
                            resDiv.innerHTML += ` | answered: ${answer}`
                        }
                    }
                }
                resultBox.append(resDiv)
            })
        },
        error: function(error){
            console.log(error)
        }
    })
}

quizForm.addEventListener('submit', e=>{
    e.preventDefault()

    sendData()
})
django ajax
© www.soinside.com 2019 - 2024. All rights reserved.