如何在提交Django-Form后将数据呈现给另一个模板?

时间:2012-05-31 11:05:54

标签: django django-forms django-templates django-views

我想做以下事情:

  • 用户将打开一个页面,即network_form.html并填写包含两个字段的表单(请参阅form.py)
  • 提交该表格后。服务器将在这两个字段的基础上执行计算,并将计算的数据呈现到另一页,即subnet_network.html
  • 看看from.py:

     class SubnetCreateFrom(forms.Form):
         Subnet_Address = forms.CharField(max_length=40)
         IP_Address = forms.CharField(max_length=40)
    

    现在我想提交这些表单字段,并希望在这些字段的基础上处理一些查询。所以,我写下面的vies.py:

     def subnet_network(request):
       if request.method == 'POST':
          form = SubnetCreateFrom(request.POST)
          if form.is_valid():
             subnet = form.data['Subnet_Address']
             ip = form.data['IP_Address']
             # Here i am manipulating the data using the above subnet and ip fields and pass the data in the form of parameter to the follwing method. i.e. get_host_list
             subnet_network_detail(request,get_hosts_list) #[1]
             return HttpResponseRedirect('../../list/')
     extra_context = {
         'form': SubnetCreateFrom(initial={'user': request.user.pk})
     }
     return direct_to_template(request, 'networks/network_form.html',
                              extra_context)
    

    模板network_form.html:

      <form action="" method="POST">
            {{ form.as_p }}
        <input type="submit" value="{% trans "Show Host" %}"/>
      </form>
    

    单击提交按钮后用户填写表单。 Ot应该打开一个显示处理数据的新页面,即get_host_list。这就是为什么我从上面定义的subnet_network方法中调用了一个subnet_network_detail方法,以便我们可以将该数据渲染到下一个模板。这是正确的方法吗?

    subnet_network_detail的定义如下:(也在相同的views.py中)

     def subnet_network_detail(request,list_hosts):
        extra_context = {
           'subnet_hosts': list_hosts
           }#[2]
        return direct_to_template(request, 'networks/subnet_network.html',
                               extra_context)
    

    以上方法的网址格式如下:

    url(r'^myapp/netmask/create/$',
        'subnet_network', name='subnet_network'),
    url(r'^myapp/netmask/select/$',
        'subnet_network_detail', name='subnet_network_detail')
    

    网址格式是否有问题。 为什么我无法将数据从SubnetCreateForm渲染到另一个模板,即subnet_network.html。这是调用该方法或将数据呈现给模板的正确方法吗?

    当我检查pdb时,发生了不同的地方:

    [1] I used the python debugger at this position and it shows an error i.e. subnet_network_detail receiving one parameter and you are passing it two
    
    [2] After removing the pdb syntax from [1] and putting at this position i check whether the data is passing to this function or not and it was. I am getting the data what i want in list_hosts variable 
    
    
    
    And also after removing the pdb syntax from [2] position it redirect to the page what we have written in HttpResponseRedirect in the first method
    

    0 个答案:

    没有答案