在Django中再次随机化 [英] Randomizing again in Django

查看:63
本文介绍了在Django中再次随机化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Django中生成测验时,if request.method =='POST':之前的问题值是1,然后更改了。请按照屏幕截图进行操作。

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

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)


推荐答案

您的视图应该看起来像这样,您只需要获取一个请求未发布时的随机问题:

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})

您的 RespostaForm 应包含一个名为 idQuestao 的字段(是ou没有显示表单的代码,但我认为它是 ModelForm )。

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

有帮助吗?

这篇关于在Django中再次随机化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆