[英]Submit a form after two clicks on submit Django
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: 这是我的views.py文件:
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. 您需要在前端使用Ajax,即使用javascript向Django后端发出异步请求,您可以使用vanilla java-script进行操作 ,或者如果已在UI中使用Jquery,则可以使用Jquery 。 I would suggest first go through the links of Vanilla java-script and understand then use Jquery. 我建议先浏览Vanilla Java脚本的链接并理解然后使用Jquery。 A more Django specific example here . 这里有一个更特定于Django的示例。 Some extracts from the above links for quick view below. 上面链接的一些摘录,以便在下面快速查看。
Using Vanilla Java-script: 使用香草Java脚本:
<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: 使用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. 希望这会有所帮助,并为您指明正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.