django没有回复适当的回应

时间:2015-09-03 11:30:37

标签: python django

我有一个带复选框和按钮的模板。我想,当我选择所有复选框并按下按钮时,它应该返回值并将其显示为httpresponse。

的index.html:

<form method="POST" action="/test/">
    {% csrf_token %}
    <div id="row-1">
        <button name="pack" id="pack">Pack</button>
    </div>
    <div id="row-2">
        <table>
            <thead>
                <tr>
                    <th><input type="checkbox" onClick="toggle(this, 'no')"></th>
                    <th>Order Id</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input type="checkbox" name="no" value="10000001">10000001</td>
                </tr>
                <tr>
                    <td><input type="checkbox" name="no" value="10000002">10000002</td>
                </tr>
            </tbody>
        </table>
    </div>
</form>

views.py:

from django.shortcuts import render, render_to_response
from django.http import HttpResponse
from test1 import forms

def index(request):
    return render(request, 'index.html')

def pack(request):
    oid_list = []
    form = forms.PackOrders(request.POST or None)
    if request.method == 'POST':
        for item in form.cleaned_data['no']:
            oid_list.append(item)
    return HttpResponse(','.join(oid_list))

urls.py:

from django.conf.urls import patterns
from django.conf.urls import url
from test1 import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^test/', views.pack, name='pack'),)

forms.py:

from django import forms

class PackOrders(forms.Form):
    order_items = forms.CharField()

问题是,当我点击复选框并返回代码时,它只是重新加载index.html而不是显示复选框的值。

预期产出:

10000001,10000002

代码有什么问题?

编辑:

项目urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include('test1.urls')),
    url(r'^test/', include('test1.urls')),
]

2 个答案:

答案 0 :(得分:2)

您已将应用程序urlconf包含在root urlconf中两次。你应该只做一次。但是,您应该从包含它的URL中删除$:

url(r'^', include('test1.urls')),

如果你使用第二个版本,使用'test /'前缀,你会在'/ test /'和'/ test / test /'创建URL,这可能不是你想要的。

请注意,正如我在评论中所说,您应该始终通过他们的名字引用网址,而不是直接引用网址。因此,您的表单操作应为"{% url 'pack' %}"

答案 1 :(得分:0)

正则表达式中的

$表示字符串的结尾,因此您的包将永远不会有机会匹配其任何网址(我想象的是您的其他urls.py)。因此,您需要将您的网址更改为包含的网址

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^/', include('test1.urls')),
    url(r'^test/', include('test1.urls')),
]

注意我已更改第二个删除$并将其替换为斜杠