Django在提交时创建一个额外的对象

2024-06-28 10:57:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在呈现页面后创建一个应答对象,当用户提供输入时,应答对象应该用新的输入更新并保存。我能够做到这一点,但由于某些原因,当用户单击submit按钮时,会创建一个额外的对象,而该对象始终为None。我使用AJAX从模板发送数据

views.py

def attention_view(request):
    participant = get_object_or_404(Participant, user=request.user)

    if request.method == 'POST':

        question_id = request.POST.get('assigned_question')
        question = get_object_or_404(Question, pk=question_id)
        answer = Answer.objects.get(participant=participant, question=question)

        if answer.answer is not None: 
            #preventing participants from changing their answer
            HttpResponse('')

        else:

            answer.answer = selected_choice
            answer.save()

    attention_question = Question.objects.get(id=13)
    answer = Answer.objects.create(participant=participant, question=attention_question)
    context = {'attention_question': attention_question, 'answer': answer}
    return render(request, 'study/AttentionCheck.html', context)

创建额外对象的原因可能是什么


Tags: or对象用户answernoneidgetobjects
1条回答
网友
1楼 · 发布于 2024-06-28 10:57:03

你的逻辑是(简化的):

    if request.method == 'POST':
        if answer.answer is not None: 
            # HttpResponse created and freed right away
            pass
        else:
            answer.answer = selected_choice
            answer.save()

    answer = Answer.objects.create(participant=participant,
      question=attention_question)

    return render(request, 'study/AttentionCheck.html', context)

请注意,1)始终调用Answer.objects.create2)始终返回呈现的AttentionCheck.html

我还注意到你在这里处理的是两个不同的问题:一个是邮寄的id问题,另一个是id为13的问题

根据您的具体要求,我认为这应该是解决方案:

def attention_view(request):
    participant = get_object_or_404(Participant, user=request.user)

    question = FIXME_WHICH_QUESTION

    answer, created = Answer.objects.get_or_create(participant=participant,
        question=question)

    if request.method == 'POST' and answer.answer is None: 
        answer.answer = selected_choice
        answer.save()

    context = {'attention_question': question, 'answer': answer}
    return render(request, 'study/AttentionCheck.html', context)

相关问题 更多 >