2016-04-13 9 views
1

非常によく似たビューとテンプレートのビューが3つあります。Djangoのビュー間でコンテキストを共有しますか?

私のコードは繰り返していて、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) 
+1

クラスベースのビューがあり、1つの汎用ビューを持つことができ、それをサブクラス化するか、またはミックスインを使用できます。https://docs.djangoproject.com/ja/1.9/topics/class-based-views/intro/ – serg

答えて

1

は、あなたが機能にそれらを抽出し、のみで渡すことができます。シャン王のアドバイスこれは、それが今どのように見えるかを以下に示し

編集

この場合はcostumer_profile_form,registrationのような結果を得るために必要なパラメータです。それから、関数を呼び出すと、その関数になるはずです。

関連する問題