0

I have written what I hope to be a re-usable Django app, but I have a bit of a conundrum on how to make the post form handling flexible. The simplified version of my view code looks like:

def do_form(request, entity_id, template_name, success_url):

    form = MyForm(request.POST or None)

    if request.method =='POST':
        if form.is_valid():

            #do some business logic

            return HttpResponseRedirect(finished_url)
    return render_to_response(template_name, 
                              {'form': form},
                             context_instance=RequestContext(request))

I have followed the advice in James Bennets book "Practical Django Projects" and so you can now configure the template and the success url in the url conf, so for example my url conf could look like this:

urlpatterns = patterns('myapp.views',


          url(r'^do/(?P<entity_id>\d+)/$', 
          view = 'do_form',
          name = 'do_form_view',
          kwargs={'template_name':'form.html',
                    'success_url':'/finish/'},),

          url(r'^finish/$', 
          view = 'finish',
          name = 'finish_view')
)

This is all very well and good but when I have come to use this in my real world application I find myself in a situation that this form sits in the middle of some workflow, and I want the success url to be something like /continue/<workflow_id>/ , and the problem is that you can only have a hardcoded url in the url conf, and the workflow_id will vary every time I hit the do_form code.

Can any one suggest a way to get around this?

4

3 回答 3

1

您可以通过更改以下内容来实现这一点..

views.pydo_form()中 更改为return HttpResponseRedirect

return HttpResponseRedirect('/continue/%s' %(workflowid))

urls.py中,您可以拥有

url(r'^continue/(?P<workflowid>\d+)/$', 
          view = 'continue',
          name = 'continue_view')

views.pycontinue()中的视图

def continue(request, workflowid=None):
 ...

这样.. 每当您访问/continue/没有数字的 url 时,workflowid 将等于None. 每隔一次,当您确实附加了一个 workflowid 时,例如 like /continue/23/,那么在您的continue()视图中,您可以通过变量访问该 id workflowid

于 2012-09-11T19:09:40.810 回答
1

当您将假设的“灵活”success_url 传递给视图时,该视图必须提供所需的标识符。因此,如果您的 URL 和视图不匹配,我们就无法避免两者之间的“违约”。

因此,如果我们要拥有灵活的 URL,就必须强制执行某种约定,如果我们通过 URL 的特殊语法来做到这一点,则不会失去一般性:

  'finished_url':  '/finish/<workflow_id>/'

然后,当然,视图必须通过字符串替换来实例化变量以兑现它的契约:而不是

  return HttpResponseRedirect(finished_url)

你将会有

  return HttpResponseRedirect(finished_url.replace('<workflow_id>', WorkflowID))

这应该使事情变得相当简单。

重用代码时,您必须记住,这<workflow_id>应用程序用来调用工作流 id 的任何内容,这就是为什么我使用复杂的字符串,例如workflow_id代替id或可能$1

编辑:我打算为下一步添加代码(在完成参数中截取工作流 ID),但我看到 keithxm23 击败了我 :-)

于 2012-09-11T19:12:35.890 回答
0

您可以像人们多年来一直“覆盖” Django 基于函数的通用视图一样做到这一点:只需将视图包装在另一个视图中:

def custom_do_form(request, entity_id, template_name, success_url):
    template_name = some_method_to_get_template()
    return do_form(request, entity_id, template_name, success_url)
于 2012-09-11T19:03:47.857 回答