gpt4 book ai didi

python - 在 Django 中的 View 之间共享上下文?

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:07 24 4
gpt4 key购买 nike

我有 3 个非常相似的 View 和模板的 View 。

我的代码变得重复,而且它似乎没有遵循 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)

最佳答案

这很正常,但解决方案确实很简单,您可以将它们提取到一个函数中,只传递生成结果所需的参数,例如 costumer_profile_formregistration 在这种情况下。然后调用该函数就可以了。

关于python - 在 Django 中的 View 之间共享上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com