2013-03-21 29 views
0

我有很多意见需要相同的功能,所以我试图将该逻辑移入一个单独的功能(而不是视图功能)。该函数在GET或会话中查找值,并返回模型实例重定向到新页面(类似于强制登录)。问题是你不能从一个被调用的函数重定向(我知道)。我应该如何处理这种情况?django可重用重定向最佳做法

这里是我的代码:

# 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)) 

我想我可以为您在视图函数的返回类型,但似乎有点凌乱。

+0

你看过基于类的视图吗?这对他们来说似乎是一个完美的场景 – miki725 2013-03-21 01:12:44

+0

尝试相反的功能 – catherine 2013-03-21 01:19:54

回答

2

装修工如何?

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 
      }) 
+0

你只是在六个不同的地方忍受我的代码。除了回答我的问题,我还学到了很多新的技巧! – Scott 2013-03-21 01:40:18

+0

如果你在其他具有不同参数的视图上使用它(除了需要“active_show”),它是如何工作的?假设,另一个视图也需要参数“scene_name”。 – Scott 2013-03-21 01:44:44

+0

对不起,我睡着了:)编辑我的答案。这是一个非常简单的改变。 – 2013-03-21 08:44:57