Randomizing again in Django

血红的双手。 提交于 2020-01-05 07:02:49

问题


When I generate a quiz in django, the question value before if request.method == 'POST': is one and then changed. Follow the screenshots.

views.py

    questao = Questao.objects.annotate(resp_count=models.Count(models.Case(models.When(resposta__usuario=request.user, then=1),output_field=models.IntegerField()))).filter(resp_count=0,tipoQuestao=1).order_by("?").first()
    print (questao)
    if request.method == 'POST':
        print (questao)
        respostaform = RespostaForm(request.POST or None)
        if respostaform.is_valid():
            resp = respostaform.save(commit=False)
            resp.idQuestao = questao
            resp.save()
        return HttpResponseRedirect(request.path_info)

回答1:


Your view should look something like this, where you only fetch a random question when the request IS NOT POST:

if request.method == 'POST':
    respostaform = RespostaForm(request.POST or None)
    if respostaform.is_valid():
        resp = respostaform.save()
    return redirect(...)
else:
    questao = Questao.objects\
        .annotate(
            resp_count=models.Count(
                models.Case(
                    models.When(resposta__usuario=request.user, then=1),
                    output_field=models.IntegerField())))\
        .filter(resp_count=0,tipoQuestao=1)\
        .order_by("?")\
        .first()
    print(questao)
    return render(request, 'some template', {'questao': questao})

Your RespostaForm should include a field named idQuestao (You did not show the code of the form, but I assume it is a ModelForm).

Does that help?



来源:https://stackoverflow.com/questions/58331696/randomizing-again-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!