У меня есть созданная страница викторины, которая проверяет, является ли ответ пользователя правильным или нет, используя функцию «проверки». Я хочу вернуть «Правильное» сообщение, если ответ правильный, и «Неверное» сообщение, если ответ неверный. Теперь я могу «отчасти» сделать это, но не совсем то, что я хочу. Теперь он возвращает сообщение после перенаправления на совершенно новую страницу с окном вопросов, а все остальное полностью исчезло, только с сообщением.
Я хочу, чтобы сообщение было показано на той же исходной странице вопроса, где-нибудь под блоком вопросов или внутри блока вопросов, без перенаправления на другую страницу или обновления страницы после отправки ответа. Я не знаю, как это сделать.
Вот мой взгляд:
class QuizView(generic.ListView):
template_name = 'geniusdennis/quiz.html'
queryset = Spanish.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# grab the max id in the database
max_id = Spanish.objects.order_by('-id')[0].id
random_id = random.randint(1, max_id + 1)
random_spanish_question = Spanish.objects.filter(id__gte=random_id)[0]
context['random_spanish_question'] = random_spanish_question
return context
Вот моя функция для проверки ответа:
def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
return render(request, 'geniusdennis/quiz.html',{
'message': "Correct!",
})
else:
return render(request, 'geniusdennis/quiz.html', {
'message': "Incorrect.",
'correct_answer': "The correct answer is " + str(coreng),
})
А вот моя HTML страница:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'geniusdennis/style.css' %}">
{% if random_spanish_question %}
<div class="flexcontainer" style="justify-content: center;">
<div class="sectiontitle">Quiz time
</div>
<div class="question_card">
<div class="question_word">{{ random_spanish_question }}</div>
<form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
<label for="ans">Answer:</label>
<input type="text" name="ans"/>
<input type="submit" value="Submit"/>
</form>
<input type="submit" value="Skip"/>
</div>
</div>
{% else %}
{% if message %}
<div class="message">
{{ message }}
</div>
<div class="ans">
{{ correct_answer }}
</div>
{% endif %}
{% endif %}