对于非常相似的视图和模板,我有3个视图。
我的代码变得重复,似乎没有遵循Django DRY 方法。
Views.py
@login_required
def registrations_check1_detail(request, registration_pk):
registration = get_object_or_404(Registration, pk=registration_pk)
costumer_profile_form = forms.CostumerProfileForm()
# THIS CONTEXT IS REPEATED ACROSS MANY OF MY VIEWS
request_context = {
'registration': registration,
'status': Registration.STATUS_CHOICES,
'costumer_profile_form': costumer_profile_form,
'duration_form': pf.DurationForm(),
'REG_DURATION_CHOICES' : Duration.REG_DURATION_CHOICES,
'EXT_DURATION_CHOICES' : Duration.EXT_DURATION_CHOICES,
'is_editable': editable_fields_perm(request.user, registration)
}
return render(request, 'profiles/registrations_check1_detail.html', request_context)
@login_required
def finance_review_detail(request, registration_pk):
costumer_profile_form = forms.CostumerProfileForm()
registration = get_object_or_404(Registration, pk=registration_pk)
request_context = {
'registration': registration,
'costumer_profile_form': costumer_profile_form,
'duration_form': pf.DurationForm(),
'REG_DURATION_CHOICES' : Duration.REG_DURATION_CHOICES,
'EXT_DURATION_CHOICES' : Duration.EXT_DURATION_CHOICES,
'is_editable': editable_fields_perm(request.user, registration)
}
return render(request, 'profiles/finance_review_detail.html', request_context)
处理此问题的正确方法是什么?
修改
按照商王的建议,这就是它现在的样子:
@login_required
def registration_detail(request, registration_pk):
request_context = _registration_context(registration_pk, request.user)
return render(request, 'profiles/registration_detail.html', request_context)
答案 0 :(得分:1)
这是正常的,但解决方案非常简单,您可以将它们提取到函数中,并且只传递生成结果所需的参数,例如costumer_profile_form
,registration
。然后你调用函数,应该是它。