在django中没有调用适当的函数

时间:2015-01-20 07:22:35

标签: django django-urls

我的django应用程序中有一个表单,它在视图中调用一个名为create的方法。该表单位于 index.html模板中。表单代码是:

的index.html

    {% if list %}
    <ul>
    {% for obj in list %}
        <li><a href="/attributes/{{ obj.attr1}}/">{{ obj.attr1 }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p><h3>Create</h3></p>
    <form action="{% url 'create' %}" method="post">
        {% csrf_token %}
        <li>Attr1: <input type="text" name="attr1" id="attr1" value="{{attr1}}" /></li><br />
        <li>Attr2: <input type="text" name="attr2" id="attr2" value="{{attr2}}" /></li><br />
        <input type="submit" value="Create" />
    </form>
{% endif %}

视图中的create函数是:

def create(request):
    print 'Create URL Matched'
    attr1 = request.POST['issuer']
    attr2 = request.POST['attr2']
    obj = IDPAttributes(a=attr1, b=attr2)
    obj.save()
    return HttpResponseRedirect(reverse('index'))

编辑:更新了attributes / urls.py

 urlpatterns = patterns('', url(r'^$', views.index, name='index'),
    url(r'^(?P<attr1>\w+)/$', views.listattr, name='listattr'),
    url(r'^edit/(?P<attr1>\w+)/$', views.edit, name='edit'),
    url(r'^edit/(?P<attr1>\w+)/update/$', views.update, name='update'),
    url(r'^create/$', views.create, name='create'),
    url(r'^delete/$', views.delete, name='delete'))

当我提交要删除的表单时,它不会进入create方法。我检查了post方法的URL,并指向http://127.0.0.1:8000/attributes/create/

这可能是什么问题? URL映射中是否存在问题?

编辑:错误地将问题中的创建URL作为删除URL

2 个答案:

答案 0 :(得分:0)

^(?P<attr1>\w+)/$正则表达式捕获所有带有/attributes/前缀的网址,因此它应该是urlpatterns中的最后一个网址:

urlpatterns = patterns('', url(r'^$', views.index, name='index'),
    url(r'^edit/(?P<attr1>\w+)/$', views.edit, name='edit'),
    url(r'^edit/(?P<attr1>\w+)/update/$', views.update, name='update'),
    url(r'^create/$', views.create, name='create'),
    url(r'^delete/$', views.delete, name='delete'),
    url(r'^(?P<attr1>\w+)/$', views.listattr, name='listattr'),

答案 1 :(得分:0)

实际上,您在创建网址中缺少^。它应该是

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