Reputation: 1334
I have 3 views for very similar views and templates.
My code is becoming repetitive and it doesn't seem to be following Django DRY approach.
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)
Which is the proper way to handle this?
Edit
Following Shang Wang's advice this is how it looks now:
@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)
Upvotes: 2
Views: 641
Reputation: 25539
That's normal, but the solution is really trivial, you could extract them into a function and only pass in the parameters that it needs to produce the result like costumer_profile_form
, registration
in this case. Then you call the function and that should be it.
Upvotes: 2