I'm doing a quiz site, and I have several questions. I currently access a certain category and is shown one question after another after clicking submit. But I would like to click once, show the response on the same screen, and after clicking it again go to the next question. How would I do that?
This is my views.py file:
class Perguntas(FormView):
form_class = QuestaoForm
template_name = 'certificacoes/pergunta.html'
template_name_result = 'certificacoes/finalizado.html'
def dispatch(self, request, *args, **kwargs):
self.dominio = get_object_or_404(Dominio, slug=self.kwargs['slug_dominio'])
try:
self.user_logado = self.request.user.is_authenticated()
except TypeError:
self.user_logado = self.request.user.is_authenticated
if self.user_logado:
self.sessao = Sessao.objects.usuario_sessao(request.user, self.dominio)
return super(Perguntas, self).dispatch(request, *args, **kwargs)
def get_form(self, *args, **kwargs):
if self.user_logado:
self.questao = self.sessao.pegar_primeira_questao()
form_class = self.form_class
return form_class(**self.get_form_kwargs())
def get_form_kwargs(self):
kwargs = super(Perguntas, self).get_form_kwargs()
return dict(kwargs, questao=self.questao)
def form_valid(self, form):
if self.user_logado:
self.form_valid_usuario(form)
if self.sessao.pegar_primeira_questao() is False:
return self.resultado_final_usuario()
self.request.POST = {}
return super(Perguntas, self).get(self, self.request)
def form_valid_usuario(self, form):
progresso = Progresso.objects.get_or_create(usuario=self.request.user)
hipotese = form.cleaned_data['respostas']
is_correta = self.questao.checar_correta(hipotese)
if is_correta is True:
self.sessao.adicionar_ponto(1)
else:
self.sessao.add_incorreta(self.questao)
# Tenho que mexer aqui para gerar uma nova questão
self.anterior = {
'resposta_escolhida': self.questao.alternativa_escolhida(hipotese),
'resposta_correta': is_correta,
'questao_resposta': self.questao.enunciado,
'respostas': self.questao.pegar_alternativas(),
'alternativa_correta': self.questao.alternativa_correta(),
'fundamento': self.questao.alternativa_fundamento(hipotese)
}
self.sessao.add_usuario_resposta(self.questao, hipotese)
self.sessao.remover_primeira_questao()
def get_context_data(self, **kwargs):
context = super(Perguntas, self).get_context_data(**kwargs)
context['questao'] = self.questao
context['dominio'] = self.dominio
context['pontos_atual'] = self.sessao.pontos_atual
context['tags'] = self.questao.get_tags
if hasattr(self, 'anterior'):
context['anterior'] = self.anterior
return context
def resultado_final_usuario(self):
resultado = {
'dominio': self.dominio,
'sessao': self.sessao,
'anterior': self.anterior,
'pontos_atual': self.sessao.pontos_atual
}
self.sessao.marcar_certificado_completo()
self.sessao.delete()
return render(self.request, self.template_name_result, resultado)
Thanks for the help anyway!
You need to use Ajax on you front-end ie Use javascript to make a asynchronous request to your Django Backend, you can do it using vanilla java-script , or use Jquery if you are already using it in UI. I would suggest first go through the links of Vanilla java-script and understand then use Jquery. A more Django specific example here . Some extracts from the above links for quick view below.
Using Vanilla Java-script:
<script> (function() { var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } })(); </script>
<button id="ajaxButton" type="button">Make a request</button>
Using Jquery:
$("ajaxButton").click(function(e){ e.preventDefault(); $.ajax({ method: "POST", url: "http://someurl.com/get", data: { name: "John", location: "Boston" } }).done(function( msg ) { alert( "Data Saved: " + msg ); }); });
Hope this helps, and points you to the right direction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.