[英]What's the best practice to deploy (manage dependency) the django reusable apps in a real production project?
[英]django reusable redirect best practice
我有很多需要相同功能的視圖,所以我試圖將該邏輯移動到一個單獨的函數(不是視圖函數)。 該函數在GET或會話中查找值並返回模型實例或重定向到新頁面(有點像強制登錄)。 問題是你無法從被調用的函數(我所知道的)重定向。 我該如何處理這種情況?
這是我的代碼:
# This is the called function
def getActiveShowOrRedirect(request):
show_pk = request.GET.get('s', False)
if not show_pk:
show_pk = request.session.get('show_pk', False)
if not show_pk:
return HttpResponseRedirect('/setup/')
active_show = Show.objects.get(pk=show_pk)
return active_show
def overview(request):
active_show = getActiveShowOrRedirect(request)
scenes = Scene.objects.filter(show=active_show)
scenes = sorted(scenes, key=lambda s: s.name)
if request.method == 'POST':
form = SceneForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
desc = form.cleaned_data['description']
scene = Scene(name=name.lower(), show=active_show, description=desc, creator=request.user)
scene.save()
return HttpResponseRedirect('/overview/')
else:
form = SceneForm(initial={'creator':request.user,'show':active_show})
return render_to_response('vfx_app/overview.html', {'active_show':active_show,'scenes':scenes,'form':form}, context_instance=RequestContext(request))
我想我可以在視圖函數中檢查返回類型,但這看起來有點混亂。
裝飾師怎么樣?
def requires_active_show(view):
"The decorated view must take active show as a second argument."
def wrapped(request, *args, **kw):
show_pk = request.GET.get('s') or request.session.get('show_pk')
if not show_pk:
return HttpResponseRedirect('/setup/')
return view(request, Show.objects.get(pk=show_pk), *args, **kw)
return wrapped
@requires_active_show
def overview(request, active_show):
scenes = Scene.objects.filter(show=active_show).order_by('name')
if request.method == 'POST':
form = SceneForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
desc = form.cleaned_data['description']
scene = Scene.objects.create(
name=name.lower(),
show=active_show,
description=desc,
creator=request.user)
return HttpResponseRedirect('/overview/')
else:
form = SceneForm(initial={'creator': request.user, 'show': active_show})
return render('vfx_app/overview.html', {
'active_show': active_show,
'scenes': scenes,
'form': form
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.