[英]How can I simplify this Django view?
我有一個向用戶顯示一些問題的應用程序。 它必須在輸入文本字段中回復,然后有一個視圖檢查所有這些結果(下一個)。
這種觀點非常有效,但我知道我對字典和列表一無所知。 我想創建這些變量只是為了准備一個結果變量,然后將其打印在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)
您可以進行以下改進以提高可讀性:
創建要訪問的輸入的列表; if
對csrf_token
字段進行if
檢查,會使代碼更難以閱讀,並且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, })
您可以更換
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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.