我有一个向用户显示一些问题的应用。它必须在输入文本字段中回复,然后有一个视图检查所有这些结果(下面的那个)。
这个观点非常有用,但我知道我弄乱了字典和列表。我想创建那些只是为了准备一个结果变量然后我将在HTML页面上打印。我该如何简化它?
def check(request):
# Initialize results
results = []
i = 0
for input_name, input_value in request.POST.items():
# Remove cfsr from inputs
if input_name.isdigit():
# Get the question from the input name
question = Question.objects.get(pk=input_name)
# Get the related correct answer to that question
answer = question.answer
# Create results
results.append({'question_text': question.text, 'user_answer': input_value,
'correct_answer': answer.text})
# Check if user answer is correct
if input_value == answer.text:
results[i]['is_correct'] = True
else:
results[i]['is_correct'] = False
i += 1
context = {'results': results}
return render(request, 'quiz/results.html', context)
答案 0 :(得分:3)
您可以根据可读性进行这些改进:
创建您要访问的输入列表;对if
字段进行csrf_token
检查会使代码更难以阅读,并且csrf_token
始终包含字母的假设可能不正确。
删除计数器变量(i
); for
循环中这样的计数器不是pythonic,通常会使代码复杂化。
if/else
测试;您可以随时使用if/else
块,只需将True
或False
分配给变量,具体取决于某些测试的结果。在追加到列表之前完全构建结果字典,以避免必须通过其索引(results[i]...
)进行访问。
from django.http import HttpResponseNotAllowed, HttpResponseBadRequest
def check(request):
if not request.method == 'POST':
return HttpResponseNotAllowed(['POST'])
# guaranteed by CsrfViewMiddleware to exist
del request.POST['csrfmiddlewaretoken']
results = []
for question_id, user_answer in request.POST.items():
try:
question = Question.objects.get(pk=name)
except Question.DoesNotExist:
return HttpResponseBadRequest("Oops!")
results.append({
'question_text': question.text,
'user_answer': user_answer,
'correct_answer': question.answer.text,
'is_correct': value == question.answer.text,
})
return render(request, 'quiz/results.html', {
'results': results,
})
答案 1 :(得分:2)
您可以替换
if input_value == answer.text:
results[i]['is_correct'] = True
else:
results[i]['is_correct'] = False
带
results[-1]['is_correct'] = input_value == answer.text
并摆脱i
甚至更好,你可以把它放在results.append
results.append({'question_text': question.text,
'user_answer': input_value,
'correct_answer': answer.text,
'is_correct': input_value == answer.text})