我试图在呈现页面后创建一个应答对象,当用户提供输入时,应答对象应该用新的输入更新并保存。我能够做到这一点,但由于某些原因,当用户单击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)
创建额外对象的原因可能是什么
你的逻辑是(简化的):
请注意,1)始终调用
Answer.objects.create
2)始终返回呈现的AttentionCheck.html我还注意到你在这里处理的是两个不同的问题:一个是邮寄的
id
问题,另一个是id
为13的问题根据您的具体要求,我认为这应该是解决方案:
相关问题 更多 >
编程相关推荐